How would I read such a JSON structure?

{"some_id":
    [
    {"city":"Bellevue"},
    {"state":"Washington"}
    ]
}
+3
source share
4 answers
var theJSonString = '({"some_id": [ {"city":"Bellevue"}, {"state":"Washington"} ] })';
var x = eval(theJSonString);
alert(x.some_id[0].city); // will display "Bellevue"
+5
source
var json = {"some_id": [ {"city":"Bellevue"}, {"state":"Washington"} ] }

json.some_id[0].city equal to "Bellevue"

and

json.some_id[1].state equals Washington

+3
source

And this (json parser and stringifier from json.org) can help :) (check the link at the bottom of the page)

0
source

All current browsers support window.JSON.parse(). It takes a formatted JSON string and returns an object or Javascript array.

Demo: http://jsfiddle.net/ThinkingStiff/KnbAJ/

Script:

var json = '{"some_id":[{"city":"Bellevue"},{"state":"Washington"}]}'
    object = window.JSON.parse( json );

document.getElementById( 'length' ).textContent = object.some_id.length;
document.getElementById( 'city' ).textContent = object.some_id[0].city;
document.getElementById( 'state' ).textContent = object.some_id[1].state;

HTML:

length: <span id="length"></span><br />
some_id[0].city: <span id="city"></span><br />
some_id[1].state: <span id="state"></span><br />

Conclusion:

length: 2
some_id[0].city: Bellevue
some_id[1].state: Washington
0
source

Source: https://habr.com/ru/post/1753442/


All Articles