问题复现

> node
> j = '{a:1,b:"2"}';
> JSON.parse(j)
SyntaxError: Unexpected token a
    at Object.parse (native)
    at repl:1:6
    at REPLServer.defaultEval (repl.js:252:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:417:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:210:10)
    at REPLServer.Interface._line (readline.js:549:8)

问题原因

示例中的j不是标准的JSON字符串,键值都得带上引号。

问题解决

使用eval

try{
    var json = JSON.parse(j);
} catch(e) {
    var json = eval("("+ j +")");
}

参考资料

http://www.json.org/json-zh.html

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐