gpt4 book ai didi

javascript循环遍历json响应

转载 作者:行者123 更新时间:2023-11-30 07:37:52 25 4
gpt4 key购买 nike

我想遍历我的 json 响应。我的 json 响应看起来像这样

{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}

我想要的是遍历所有行的 foreach 循环,以便我获得每一行的键和值。

最佳答案

您可以这样迭代:(添加代码注释以进行解释)

var result = document.getElementById("result");
var json = '{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}';

var obj = JSON.parse(json);
// json object contains two properties: "line" and "total".
// iterate "line" property (which is an array but that can be iterated)
for (var key in obj.line) {
// key here is the index of line array
result.innerHTML += "<br/>" + key + ": ";
// each element of line array is an object
// so we can iterate over its properties
for (var prop in obj.line[key]) {
// prop here is the property
// obj.line[key][prop] is the value at this index and for this prop
result.innerHTML += "<br/>" + prop + " = " + obj.line[key][prop];
}
}
// "total" is a property on the root object
result.innerHTML += "<br/><br/>Total = " + obj.total;
<p id="result"> </p>

演示 fiddle :http://jsfiddle.net/abhitalks/ajgrLj0h/2/

.

关于javascript循环遍历json响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26910816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com