jquery decode json object with double quoted keys
Question
I have a script that outputs a json string via json_encode in PHP. The json string consists of
[{"custId":"2","custName":"John Inc"}]
The PHP script is initiated using
$.getJSON("customer.php", function(data){alert(data + ' ' + data.custName);});
The response is -
[object Object] undefined
Javascript recognises 'data' as an object but I cannot seem to reference the information using json dotted notation.
Solution
The data
object is in an array so you need to access its elements keyed by an index:
alert(data[0].custName);
Also, I'd suggest installing firebug (assuming you are already using Firefox) and using console.log
in lieu of alert.
Its output is much more detailed and helpful.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow