0

I am trying to parse JSON, but it gives the wrong result.

var obj = JSON.parse('[{ "name":"John", "age":30, "city":"New York"}]');

alert(obj);

Please check the code and provide me any suggestion.

3
  • 1
    you cannot alert object use console.log(obj); Commented Dec 28, 2017 at 10:18
  • 1
    There is nothing wrong, you are parsing an array. Open the console of your browser and try: var obj = JSON.parse('[{ "name":"John", "age":30, "city":"New York"}]'); obj[0]; // this will print an object. Commented Dec 28, 2017 at 10:23
  • "it gives the wrong result" — It gives the result I'd expect it to give. What result do you expect it to give? Commented Dec 28, 2017 at 10:39

3 Answers 3

3

You can not alert() objects. So Use console.log() instead of alert().

By The Way you can alert() individual values.

Working snippet:-

var obj = JSON.parse('[{ "name":"John", "age":30, "city":"New York"}]');
console.log(obj);

alert(obj[0].name); // you can alert values
alert(obj[0].age);  // you can alert values
alert(obj[0].city); // you can alert values

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

2 Comments

Thanks for this valuable answer, I have one more question, can i ask?
@AshishRana yes you can ask.
0

You can also use eval() to parse json string

var test = '[{ "name":"John", "age":30, "city":"New York"}]';
var obj = eval ("(" + test + ")");

console.log(obj);
//console.log(obj[0].name);

Comments

0
     You have an array in json object you can get the json object
     values by referencing the key name.

     alert(obj[0].name);
     alert the value of json object at 0 index and by providing the key name.

 <script>
 var obj = JSON.parse('[{ "name":"John", "age":30, "city":"New York"}]');
 alert(obj);

   alert(obj[0].name);
  </script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.