0

我试图弄清楚如何访问 JSON 格式的数据,并且已经花了一整天的时间寻找方法,但我仍然找不到满足我需求的解决方案。与我的问题最接近的相关问题是这个问题,但无济于事。

基本上我正在检索$.ajax()以 JSON 格式返回的数据。

[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]

我的问题是如何访问 JSON 中的元素,比如我想在 javascript 中获取第二个括号中的所有“nv”值或“date”的所有值?我对这些东西很陌生,所以不熟悉这些术语,对此感到抱歉。

下面是我的代码:

var Data = $.ajax({
    url: url,
    type: 'POST',
    dataType:"json",
    async: false
}).responseText;

console.log(Data);

url是一个在我的函数内部传递的变量,以防你问。

4

2 回答 2

4

更新:请参阅 Anthony Grist 对您的问题的评论,我错过了您的 JSON 无效的事实。由于他没有发布答案,我会去接它。

您的JSON无效,因为您要返回两个单独的数组,这是一个:

[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]

和这个:

[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]

你不能这样做,因为 JSON 文档的顶层必须是一个东西(一个对象或一个数组)。

您可以返回一个包含每个数组属性的对象:

{
"vdata":
    [{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
     {"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
     {"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
    ],
"datedata":
    [{"date":"2013-02-01","visits":63},
     {"date":"2013-02-02","visits":30}
    ]
}

解析后(见下文),您可以像这样访问该数据:

console.log(data.vdata[0].v); // "233"
console.log(data.datedata[0].date); // "2013-02-01"

或者一个有两个插槽的数组,每个插槽中都有一个数组:

[
    [{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
     {"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
     {"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
    ],
    [{"date":"2013-02-01","visits":63},
     {"date":"2013-02-02","visits":30}
    ]
]

解析后(见下文),您可以像这样访问该数据:

console.log(data[0][0].v); // "233"
console.log(data[1][0].date); // "2013-02-01"

就个人而言,我更喜欢使用对象,因为从那时起我就很清楚我正在访问哪个数组。


原答案:

jQuery 会将 JSON 解析为您的对象并将其传递给success函数,然后您可以像访问任何其他对象一样访问该函数。在您的情况下,顶层是一个数组。所以:

$.ajax({
    url: url,
    type: 'POST',
    dataType:"json",
    async: false,
    success: function(data) {
        // Use the line from above that suits the way
        // you updated your JSON structure
    }
});

旁注:async: false已弃用,将在某个时候删除。做同步 ajax 请求通常不是一个好主意,它往往会在请求期间锁定浏览器的 UI。success相反,只需构建代码以在触发回调时继续处理。

于 2013-02-22T09:29:19.987 回答
1

如果我理解您的问题,您需要为此数组中的所有对象访问相同的键。

没有直接的方法可以做到这一点,您必须遍历此数组中的所有对象,然后在每个对象中找到所需的键。

JSON.parse() 会将此字符串转换为 Javascript 对象 (JSON)

var myData = JSON.parse(Data);

for(var i = 0; i < myData.length; i++) {
    console.log("This is the nv value of the " + i + " object: " + myData[i].nv);
}
于 2013-02-22T09:35:15.630 回答