[英]Why does JSON.parse give invalid character
Edit: Solved... I needed to use JSON.stringify() here. 编辑:解决...我需要在这里使用JSON.stringify()。 Doh.
h
I am trying to JSON.parse() a response token and keep getting "SyntaxError: Invalid character" in Internet Explorer. 我正在尝试JSON.parse()一个响应令牌,并在Internet Explorer中不断获取“ SyntaxError:无效字符”。 (Not sure if this issue is present in Chrome due to CORS, but that's a different issue.)
(不确定由于CORS导致Chrome中是否存在此问题,但这是另一个问题。)
console.log(response.token.isAdmin)
// false
console.log(JSON.parse(response.token.isAdmin))
// false
console.log(response.token.tokenValue)
// 36151b9e-ad0d-49de-a14b-5461489c7065
console.log(JSON.parse(response.token.tokenValue.toString()))
// SyntaxError: Invalid character
The same error occurs for any string I am trying to parse. 我尝试解析的任何字符串都会发生相同的错误。 If the source is not a string (boolean, integer) the parsing works fine.
如果源不是字符串(布尔值,整数),则解析正常。
Why isn't this working and how can I put my object into a string? 为什么这样做不起作用,如何将对象放入字符串中?
36151b9e-ad0d-49de-a14b-5461489c7065
is invalid JSON. 36151b9e-ad0d-49de-a14b-5461489c7065
无效的JSON。
JSON.parse('36151b9e-ad0d-49de-a14b-5461489c7065'); // SyntaxError
Maybe you meant "36151b9e-ad0d-49de-a14b-5461489c7065"
, which is valid JSON. 也许您的意思是
"36151b9e-ad0d-49de-a14b-5461489c7065"
,它是有效的JSON。
JSON.parse('"36151b9e-ad0d-49de-a14b-5461489c7065"');
// 36151b9e-ad0d-49de-a14b-5461489c7065
Or maybe you wanted to stringify to JSON instead of parse 也许您想将其字符串化为JSON而不是解析
JSON.stringify('36151b9e-ad0d-49de-a14b-5461489c7065');
// "36151b9e-ad0d-49de-a14b-5461489c7065"
It appears that you are trying to parse a string that is not valid JSON. 看来您正在尝试解析无效的JSON字符串。
You could parse a string like this: 您可以这样解析一个字符串:
var parseMe = '{ "tokenValue": "36151b9e-ad0d-49de-a14b-5461489c7065" }';
var parsed = JSON.parse(parseMe);
// parsed is now equal to Object {tokenValue: "36151b9e-ad0d-49de-a14b-5461489c7065"}
But you cannot parse something that is not formatted as JSON, like this: 但是您无法解析未格式化为JSON的内容,如下所示:
var parseMe = '36151b9e-ad0d-49de-a14b-5461489c7065';
var parsed = JSON.parse(parseMe);
// Uncaught SyntaxError: Unexpected token b in JSON at position 5
If instead you wanted to get a JSON object parsed as a string, you could use JSON.stringify()
like so: 相反,如果您想将JSON对象解析为字符串,则可以使用
JSON.stringify()
如下所示:
var stringifyMe = { tokenValue: '36151b9e-ad0d-49de-a14b-5461489c7065' };
var stringified = JSON.stringify(stringifyMe);
// stringified is now equal to the string {"tokenValue":"36151b9e-ad0d-49de-a14b-5461489c7065"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.