最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js JSON.parse(string) is returning a string - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论