Reputation: 5766
I'm trying to parse returned json but can't access the data.
Trying to access url value from data array.
The return looks like this below:
{ "status_code": 200, "status_txt": "OK", "data": { "long_url": "http:\/\/stackoverflow.com\/questions\/327231\/best-way-to-display-data-via-json-using-jquery", "url": "http:\/\/bit.ly\/u0GIx8", "hash": "u0GIx8", "global_hash": "7d5klp", "new_hash": 0 } }
This won't do the trick:
alert(json.data[url]);
I'm using jQuery method getJSON to send query.
Upvotes: 0
Views: 219
Reputation: 38121
Note that when using the []
notation to index into JSON objects, you need to provide a string, i.e. a quoted sequence of characters. Without the quotes, it thinks you are trying to use the value of some variable called url
, which more than likely doesn't exist.
So what you had is the same as:
alert(json.data[undefined]);
Which obviously won't work.
For clarity's sake, being consistent with which way you access the properties is probably best - use either the object.property
notation, or the object['property']
notation.
Upvotes: 1
Reputation: 287885
You want json.data.url
, or equivalently one of json['data']['url']
, json.data['url']
or json['data'].url
.
Without quotes, data[url]
refers to the key with the value of the variable url
, not the key with the name 'url'
. Provide a static string in brackets or use the dot-notation to get the value associated with a static key.
Upvotes: 3