The standard way to parse JSON in JavaScript is JSON.parse()
(在JavaScript中解析JSON的标准方法是JSON.parse()
)
The JSON
API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js.(JSON
API是在ES5 (2011)中引入的,此后按市场份额和Node.js在超过99%的浏览器中已实现。) Its usage is simple:(它的用法很简单:)
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);
The only time you won't be able to use JSON.parse()
is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs.(唯一无法使用JSON.parse()
是,如果您正在为旧版浏览器进行编程,例如IE 7(2006),IE 6(2001),Firefox 3(2008),Safari 3.x (2009)等。或者,您可能处于不包含标准API的深奥JavaScript环境中。) In these cases, use json2.js , the reference implementation of JSON written by Douglas Crockford , the inventor of JSON.(在这些情况下,请使用JSON2.js ,这是JSON的发明者Douglas Crockford编写的JSON参考实现。) That library will provide an implementation of JSON.parse()
.(该库将提供JSON.parse()
的实现。)
When processing extremely large JSON files, JSON.parse()
may choke because of its synchronous nature and design.(在处理极大的JSON文件时, JSON.parse()
可能由于其同步特性和设计而感到窒息。) To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet , which provide streaming JSON parsing.(为了解决这个问题,JSON网站推荐了第三方库,例如Oboe.js和clarinet ,它们提供了流JSON解析。)
jQuery once had a $.parseJSON()
function, but it was deprecated with jQuery 3.0.(jQuery曾经有一个$.parseJSON()
函数,但jQuery 3.0弃用了它。) In any case, for a long time it was nothing more than a wrapper around JSON.parse()
.(无论如何,很长一段时间以来,它只不过是JSON.parse()
的包装。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…