jquery decode json object with double quoted keys-Collection of common programming errors

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.

  1. 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.

Originally posted 2013-11-09 22:55:04.