How To Use The Json?
I have called an api using href from the html form and it in response gives json as output. consider this as the json the api gives { 'entry': { 'id': '1', 'name': 'SA' } } I want
Solution 1:
I want the values of the city_id and city_name. How can i get the values specifically and store those values to a variable
Use JSON.parse
to convert it to JS object and get your values:
var obj = JSON.parse(yourJSON);
var city_id = obj['entry']['city_id'];
var city_name = obj['entry']['city_name'];
Docs:
Solution 2:
var a;
eval('a={"entry":{"@collection_url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f4602e2c000016","@created_at": "2012-06-21T09:12:40Z","@trash": false,"@type": "City","@updated_at": "2012-06-21T09:12:40Z","@url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f460e2c000016/entries/4fe2e58898f4604757000006","@version": 1,"city_id": "City_001","city_name": "London"}}');
in other words
eval ('a={/*response object*/}')
now you have (a) as object that contains your data you can access them whether like object notation (a.entry) or as an array (a['entry']) you can also use json parse but its not compatible with all browsers
Solution 3:
Either the eval() function or the JSON parser will allow you to create an object from the JSON and then access the fields normally. The JSON parser is a little more secure, as explained in this tutorial:
Post a Comment for "How To Use The Json?"