Bruno Thileeban
Bruno Thileeban

Reputation: 15

How read the json in javascript?

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

Answers (3)

Joseph
Joseph

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.

  1. 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"}}}');
    
  2. 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

Snuffleupagus
Snuffleupagus

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

lukecampbell
lukecampbell

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

Related Questions