在JavaScript中解析JSON? [重复]

本文翻译自:Parse JSON in JavaScript? [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 4 years ago . 4年前关闭。

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.resultjsonObject.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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值