Reputation: 15
Can you tell me how to read the json in javascript?
I have a json string as bellow
{"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile":"0123","landline":"01234","skype":"01235"}}}
I want to read the skype phone number
Upvotes: 0
Views: 295
Reputation: 119847
If you are starting out with a JSON string, start with 1
. If you already have a JS object, then skip to 2
.
Parse the string using JSON.parse()
to convert JSON string to a JS object. To support a browser that does not have the native JSON, you can use Crockford's JSON2 library to implement it.
var jsondata = JSON.parse('{"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile":"0123","landline":"01234","skype":"01235"}}}');
Retrieve the value like you normally would from a JS object
var skype = jsondata.person['phone number'].skype;
Here's the full code and a sample:
var jsondata = JSON.parse('{"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile":"0123","landline":"01234","skype":"01235"}}}');
//normally, the dot-notation is used
//but since "phone number" is not a valid key when using dot-notation
//the bracket notation is used
var skype = jsondata.person['phone number'].skype;
Upvotes: 6
Reputation: 6725
First it needs to be parsed out to a native javascript object, in modern browsers this can be done via JSON.parse(json string here);
. Now to specifically get to the skype number you have the object you just parsed out. Let's pretend you assigned it via var skypeData = JSON.parse(json string here);
, the persons skype number is accessible via skypeData.person['phone number'].skype
. We have to use ['phone number']
instead of person.phone number.skype
because of the space.
Upvotes: 0
Reputation: 15256
This should get you on your way.
var o = {"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile":"0123","landline":"01234","skype":"01235"}}}
o["person"]["phone number"]["skype"];
/* or */
o.person["phone number"]["skype"];
Upvotes: 5