在 JavaScript 中解析 JSON? [英] Parse JSON in JavaScript?

查看:29
本文介绍了在 JavaScript 中解析 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 JavaScript 解析一个 JSON 字符串.响应类似于

I want to parse a JSON string in JavaScript. The response is something like

var response = '{"result":true,"count":1}';

我怎样才能得到resultcount 的值?

How can I get the values result and count from this?

推荐答案

在 JavaScript 中解析 JSON 的标准方法是 JSON.parse()

The standard way to parse JSON in JavaScript is JSON.parse()

JSON API 是在 ES5 (2011) 中引入的,此后在 >99% 的浏览器市场份额,以及 Node.js.它的用法很简单:

The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:

const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);

唯一无法使用 JSON.parse() 的情况是,如果您正在为古老的浏览器编程,例如 IE 7 (2006)、IE 6 (2001),Firefox 3 (2008)、Safari 3.x (2009) 等.或者,您可能处于不包含标准 API 的深奥 JavaScript 环境中.在这些情况下,请使用 json2.js,参考实现JSON 由 JSON 的发明者 Douglas Crockford 编写.该库将提供 JSON.parse() 的实现.

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. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse().

在处理极大的 JSON 文件时,JSON.parse() 可能会因为其同步性质和设计而窒息.为了解决这个问题,JSON 网站推荐使用第三方库,例如 Oboe.jsclarinet,提供流式 JSON 解析.

When processing extremely large JSON files, JSON.parse() may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet, which provide streaming JSON parsing.

jQuery 曾经有一个 $.parseJSON() 函数,但它已被 jQuery 3.0 弃用.无论如何,在很长一段时间内,它只不过是对 JSON.parse() 的包装.

jQuery once had a $.parseJSON() function, but it was deprecated with jQuery 3.0. In any case, for a long time, it was nothing more than a wrapper around JSON.parse().

这篇关于在 JavaScript 中解析 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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