0

How to parse json?

var text = '{"body":[
              {"name":"name","value":"test1"},
              {"name":"inquiry_type","value":"test2"}
            ]}'; 
console.log(text);
var obj = JSON.parse(text.body);
cosole.log (obj);

Here obj console displaying error.

4 Answers 4

3

You're supposed to extract body after you parse your JSON, not before.

var text = `{"body":[
          {"name":"name","value":"test1"},
          {"name":"inquiry_type","value":"test2"}
        ]}`; 

var obj = JSON.parse(text).body;
console.log(obj)  //note that you misspelled this too
Sign up to request clarification or add additional context in comments.

Comments

2

For multiline statements, use template literals. Your JSON string is text, once you parse it you will get an object on which you can access body property using dot notation or bracket notation.

var text = `{"body":[
              {"name":"name","value":"test1"},
              {"name":"inquiry_type","value":"test2"}
            ]}`; 
console.log(text);
var obj = JSON.parse(text).body;
console.log (obj);

Comments

1

Your variable text is a multiline string you must use template string :

var text = `{"body":[
          {"name":"name","value":"test1"},
          {"name":"inquiry_type","value":"test2"}
        ]}`;

or write it in single line :

var text = '{"body":[{"name":"name","value":"test1"},{"name":"inquiry_type","value":"test2"}]}'; 

And you must save the parsed text in a variable like that :

var text = '{"body":[{"name":"name","value":"test1"},{"name":"inquiry_type","value":"test2"}]}'; 

text = JSON.parse(text);
console.log(text);
var obj = text.body;
console.log(obj);

Comments

-3

JSON.parse() takes a string of JSON and parses it, as the name suggests.

You have an array, not a string of JSON, so you don't need to do anything.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.