I have a JSON object as a string, I am parsing it with JSON.parse() but the resulting object is still a string. Am I doing something wrong?
var myString = "{Username:Brad,Password:12345}";
// adding in the quotes or else it throws an error saying 'unidentified token U
var myJson = JSON.parse('"' + myString + '"');
console.log(myJson.Username); // prints 'undefined'
console.log(typeof(myJson)); // prints 'string'
I have a JSON object as a string, I am parsing it with JSON.parse() but the resulting object is still a string. Am I doing something wrong?
var myString = "{Username:Brad,Password:12345}";
// adding in the quotes or else it throws an error saying 'unidentified token U
var myJson = JSON.parse('"' + myString + '"');
console.log(myJson.Username); // prints 'undefined'
console.log(typeof(myJson)); // prints 'string'
Share
Improve this question
asked Jan 11, 2016 at 3:33
BradStellBradStell
5004 silver badges19 bronze badges
2
-
3
The string is not a valid representation of JSON. The keys and values should be wrapped in quotes.
var obj = JSON.parse('{"Username": "Brad","Password": "12345"}');
Use JSONLint to check if your JSON is valid. – Tushar Commented Jan 11, 2016 at 3:34 - Thank you, that was the issue. Quotes were there in my client, and for some reason in the response in my server they disapeared. – BradStell Commented Jan 11, 2016 at 3:40
1 Answer
Reset to default 5That's not valid JSON. keys and strings need to be quoted:
var myString = '{"Username":"Brad","Password":12345}';
var myJson = JSON.parse( myString );
See json for information about JSON.