Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  101] [ 7]  / answers: 1 / hits: 54227  / 9 Years ago, thu, october 29, 2015, 12:00:00

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.


More From » json

 Answers
5

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])
);
}




[#64565] Monday, October 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;