[英]How do I get data from JSON in JavaScript?
I have a JSON and I need to get the values of 'pk' and 'cnt' from it: 我有一个JSON,我需要从中获取“ pk”和“ cnt”的值:
[{
"ip": "[{"pk": "173.194.44.23",
"model": "link_finder.ip",
"fields": {"cnt": 3}},
{"pk": "173.194.44.24",
"model": "link_finder.ip",
"fields": {"cnt": 3}}]",
"urls": "[{"pk": "http:\\google.com\advanced_search?hl=uk&authuser=0",
"model": "link_finder.url",
"fields": {"cnt": 2}},
{"pk": "http:\\google.com\intl\uk\about.html",
"model": "link_finder.url",
"fields": {"cnt": 2}}]"
}]
I know how to put it in an array, but how do I get, for example, the pk and cnt walues from first and second paragraph ? 我知道如何将其放入数组中,但是如何从第一段和第二段得到pk和cnt字呢?
Updated because the code changed: 已更新,因为代码已更改:
If the object is named ip
, then: 如果对象名为ip
,则:
data[0].ip[0].pk
data[0].ip[0].fields.cnt
data[1].ip[1].pk
data[1].ip[1].fields.cnt
Original answer : 原始答案 :
You're missing the array brackets for this to be valid JSON. 您缺少将其作为有效JSON的数组括号。
Also assuming that you're getting this JSON from some sort of Ajax-y thing, and that it's sending back the JSON in an object called 'data'. 还要假设您是从某种Ajax-y事物中获取此JSON,并且它正在将JSON发送回称为“数据”的对象中。
If you had the array brackets, the syntax would be: 如果有数组括号,则语法为:
data[0].pk //123.104.44.23
data[0].fields.cnt // 159
data[1].pk //171.154.44.24
data[1].fields.cnt // 159
This would be in Javascript, though looking at it that syntax would work for Python as well. 这将用Javascript编写,尽管看着它语法也适用于Python。
Check the next code. 检查下一个代码。
var json = {};
json = [{"pk": "123.104.44.23",
"model": "link_finder.ip",
"fields": {"cnt": 159}},
{"pk": "171.154.44.24",
"model": "link_finder.ip",
"fields": {"cnt": 159}},
{"pk": "172.194.34.31",
"model": "link_finder.ip",
"fields": {"cnt": 159}}];
for (var key in json){ console.log(json[key].pk + ' ' + json[key].fields.cnt)}
Result: 结果:
123.104.44.23 159
171.154.44.24 159
172.194.34.31 159
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.