Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from json "undefined" what I have wrong?

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.

like image 388
BigBugCreator Avatar asked Nov 27 '22 05:11

BigBugCreator


2 Answers

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"])
   );
} 
like image 107
Quentin Avatar answered Nov 29 '22 18:11

Quentin


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...

like image 35
Get Off My Lawn Avatar answered Nov 29 '22 19:11

Get Off My Lawn