JSON Lint说它有效但JSON.parse会抛出错误 [英] JSON Lint says it's valid but JSON.parse throws error

查看:224
本文介绍了JSON Lint说它有效但JSON.parse会抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的JSON,我需要解析到对象。奇怪的是,即使我将我的JSON字符串复制并粘贴到JSONLint,它也不起作用( http://jsonlint.com/)它将显示它是有效的。

I have simple JSON that I need to parse to object. Strangely it doesn't work even though if I copy and paste my JSON string to JSONLint (http://jsonlint.com/) it will show that it's valid.

var string = '{"token":"9eebcdc435686459c0e0faac854997f3","email":"201403050007950","id":"13","updated_at":"2014-03-05 10:34:51","messageguides":"[{\"name\":\"Un-named Messaging Guide 1\",\"pages\":[\"sustainabilitydirectors\",\"marketingnbusinessdevelopmentdirectors\"],\"date\":1394015692958}]"}';

var obj = JSON.parse(string); // Unexpected token n

console.log(obj);


推荐答案

\ 字符被视为JSON转义字符。

The \ characters in the data are treated as JSON escape characters when you parse the raw JSON.

当您将JSON嵌入JavaScript字符串中时,它们会被处理as JavaScript 转义字符,而不是JSON转义字符。

When you embed that JSON inside a JavaScript string, they are treated as JavaScript escape characters and not JSON escape characters.

您需要将它们转义为 \\ 当你将JSON表达为JavaScript字符串时。

You need to escape them as \\ when you express your JSON as a JavaScript string.

这就是说,你通常会更好将JSON作为对象(或数组)文字放入JavaScript中,而不是将其嵌入到字符串中,然后将其解析为单独的步骤。

That said, you are usually better off just dropping the JSON in to the JavaScript as an object (or array) literal instead of embedding it in a string and then parsing it as a separate step.

var obj = {"token":"9eebcdc435686459c0e0faac854997f3","email":"201403050007950","id":"13","updated_at":"2014-03-05 10:34:51","messageguides":"[{\"name\":\"Un-named Messaging Guide 1\",\"pages\":[\"sustainabilitydirectors\",\"marketingnbusinessdevelopmentdirectors\"],\"date\":1394015692958}]"};

这篇关于JSON Lint说它有效但JSON.parse会抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆