简体   繁体   中英

Problems with parsing JSON in Javascript

I pass this variable strJSON to the client page. This variable contains this data:

[{"firstName":"Michael","lastName":null,"emails":["John@gmail.com"]},
 {"firstName":null,"lastName":null,"emails":["Michael@gmail.ru"]},
 {"firstName":"Olga","lastName":null,"emails":["mailOlga@gmail.com"]}]

I try to parse Json to JavaScript object:

var parsedJSON = JSON.parse(strJSON);

But in the row above I get this error:

SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data

I think that I get error because the JSON have to be in single quotes, so before I parse the JSON I do this:

strJSON= "'" + str + "'";

But after I added the row above, I in this row :

var parsedJSON = JSON.parse(strJSON);

I get this error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Any idea what I do wrong? Thank you in advance.

first stringify the json then parse :

var str=[{"firstName":"Michael","lastName":null,"emails":["John@gmail.com"]},
 {"firstName":null,"lastName":null,"emails":["Michael@gmail.ru"]},
 {"firstName":"Olga","lastName":null,"emails":["mailOlga@gmail.com"]}];

var parsedJSON = JSON.parse(JSON.stringify(str));

console.log(parsedJSON);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM