6

I have this string:

[
 {"id":"001",
  "name":"Charlie"},
  {"id":"002",
  "name":"Ellie"},
]

Them, I save this string in a variable and I parse it:

function parseJSON(string){
   var mylovelyJSON = JSON.stringify(string); 
   alert(mylovelyJSON[id]); 
} 

When I make my alert, I get and "undefined", I also tried with "mylovelyJSON.id", And I get the same.

Could not be a Json? I get this string from an php array.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
BigBugCreator
  • 1,009
  • 4
  • 17
  • 34
  • You parse it wrong, should be `JSON.parse(string); ` – antyrat Oct 29 '15 at 15:43
  • 1
    With json.parse I get "object Object],[object Object]" I dont get the value of my id´s. – BigBugCreator Oct 29 '15 at 15:45
  • Are you trying to reference it by "001" or the index of the array? And you are making a string, not an object. `stringify` is taking an object and making a string. If it is producing object, object, than you already have an object and do not need to parse it. – epascarello Oct 29 '15 at 15:48

2 Answers2

32

There are many things wrong here

Your JSON is invalid

You have an extra , just before the end of the array that you need to remove

You need to parse

JSON.stringify converts a JavaScript data structure into a string of JSON.

You need to go the other way and use JSON.parse.

Square-bracket notation takes strings

mylovelyJSON[id] takes the value of id (which is undeclared so, in this case, would throw a reference error) and gets the property with the name that is the same as that value.

You need either mylovelyJSON["id"] or mylovelyJSON.id

You have an array

Your JSON consists of an array of objects, not a single object.

You need to get an object out of the array before you can access properties on it.

mylovelyJSON[0]["id"]


var json_text = '[{"id":"001","name":"Charlie"},{"id":"002","name":"Ellie"}]';

parseJSON(json_text);

function parseJSON(string){
   var result_of_parsing_json = JSON.parse(string);
   document.body.appendChild(
     document.createTextNode(result_of_parsing_json[0]["id"])
   );
} 
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I think this really answered by question. Also, more people can use this method of variable naming while answering queries instead of honestly bar/foo or a, x. Well done. – CoderX Mar 08 '20 at 14:58
  • I did not saw any answer like this. Well documented. Step by step solution. Thank you – Ashok May 13 '21 at 17:39
2

Two things are wrong here

  1. Your array ends with a comma, which isn't valid json
  2. You are converting a string to javascript, and stringify does the opposite of that.

So something like this might work:

var id = 0;

function parseJSON(string){
    var mylovelyJSON = JSON.parse(string); 
    alert(mylovelyJSON[id]); 
}

Note I am assuming that id is a global variable...

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338