5

Hi i have the below json

{id:"12",data:"123556",details:{"name":"alan","age":"12"}}

i used the code below to parse

var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}}
var jsonobj = JSON.parse(chunk);
console.log(jsonobj.details);

The output that i received is

{"name":"alan","age":"12"}

I need to get the individual strings from details say i should be able to parse and get the value of "name".I am stuck here any help will be much appreciated

2
  • Try chunk["details"]["name"] Commented Jan 8, 2013 at 5:28
  • You should quote it if you want to make it json. Otherwise its JS object literal Commented Jan 8, 2013 at 5:30

2 Answers 2

27

If you already have an object, you don't need to parse it.

var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}};
// chunk is already an object!

console.log(chunk.details);
// => {"name":"alan","age":"12"}

console.log(chunk.details.name);
//=> "alan"

You only use JSON.parse() when dealing with an actual json string. For example:

var str = '{"foo": "bar"}';
console.log(str.foo);
//=> undefined

// parse str into an object
var obj = JSON.parse(str);

console.log(obj.foo);
//=> "bar" 

See json.org for more details

Sign up to request clarification or add additional context in comments.

Comments

1

Since jsonobj has already been parsed as a JavaScript Object, jsonobj.details.name should be what you need.

2 Comments

jsonobj has be re-parsed. The whole parsing part can be skipped because chunk is already an object.
OK, I thought chunk was a string, otherwise parse make no sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.