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.
There are many things wrong here
You have an extra ,
just before the end of the array that you need to remove
JSON.stringify
converts a JavaScript data structure into a string of JSON.
You need to go the other way and use JSON.parse
.
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
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"])
);
}
Two things are wrong here
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With