本文翻译自:Parse JSON in JavaScript? [duplicate]
I want to parse a JSON string in JavaScript. 我想解析JavaScript中的JSON字符串。 The response is something like 响应就像
var response = '{"result":true,"count":1}';
How can I get the values result
and count
from this? 我如何获得数值result
并从中进行count
?
#1楼
参考:https://stackoom.com/question/Khyy/在JavaScript中解析JSON-重复
#2楼
If you are getting this from an outside site it might be helpful to use jQuery's getJSON. 如果您是从外部站点获得的,那么使用jQuery的getJSON可能会有所帮助。 If it's a list you can iterate through it with $.each 如果是列表,则可以使用$ .each遍历它。
$.getJSON(url, function (json) {
alert(json.result);
$.each(json.list, function (i, fb) {
alert(fb.result);
});
});
#3楼
I thought JSON.parse(myObject)
would work. 我认为JSON.parse(myObject)
可以工作。 But depending on the browsers, it might be worth using eval('('+myObject+')')
. 但是根据浏览器的不同,可能值得使用eval('('+myObject+')')
。 The only issue I can recommend watching out for is the multi-level list in JSON. 我可以建议注意的唯一问题是JSON中的多级列表。
#4楼
If you want to use JSON 3 for older browsers, you can load it conditionally with: 如果要对较旧的浏览器使用JSON 3 ,则可以有条件地通过以下方式加载它:
<script>
window.JSON ||
document.write('<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js"><\/scr'+'ipt>');
</script>
Now the standard window.JSON
object is available to you no matter what browser a client is running. 现在,无论客户端运行哪种浏览器,都可以使用标准的window.JSON
对象。
#5楼
You can either use the eval function as in some other answers. 您可以像其他一些答案一样使用eval函数。 (Don't forget the extra braces.) You will know why when you dig deeper), or simply use the jQuery function parseJSON
: (别忘了多余的花括号。)当您深入研究时,您会知道为什么),或者干脆使用jQuery函数parseJSON
:
var response = '{"result":true , "count":1}';
var parsedJSON = $.parseJSON(response);
OR 要么
You can use this below code. 您可以使用以下代码。
var response = '{"result":true , "count":1}';
var jsonObject = JSON.parse(response);
And you can access the fields using jsonObject.result
and jsonObject.count
. 您可以使用jsonObject.result
和jsonObject.count
访问这些字段。
#6楼
The following example will make it clear: 下面的示例将使其变得清晰:
let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);
// Output: John Doe, 11