使用循环遍历JSON而不修改数据 [英] Traversing in JSON with loop without modifying data

查看:87
本文介绍了使用循环遍历JSON而不修改数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的JSON数据,我想用循环遍历它,但是data.length返回1而它应该返回2.

请帮我解释如何遍历循环数据而不修改它



I have a JSON data as shown below, I want to traverse into it with loop, but data.length is returning 1 while it should return 2.
Please help me out how can I traverse into data with loop without modifying it

var data=[{
"468040": {
"Author": "William von Hagen",
"Title": "Ubuntu Linux Bible"
},
"541115": {
"Author": "Lohith G.N.",
"Title": "Windows Phone 7.5 Application Development with F#"
}
}]
alert(data.length);  //returning 1 instead of 2

推荐答案

嗯......首先,json看起来对我不好,但是你可以做这样的事情来展示所有的结构:



Well...first of all that json doesn't look good to me, but you could do something like this to show all the structure:

for (key in data[0])
{
	console.log(key);
	for (key2 in data[0][key])
	{
		console.log(" " + key2);
		console.log("   " + data[0][key][key2]);
	}
}


错误符合您的期望。

数据是一个包含1个对象的数组该对象包含2个对象/属性。

如果长度等于2,则需要

The error is on your expectations.
Data is an array containing 1 object and the object contains 2 objects/properties.
To have length equal to 2, you need
var data=[
"468040":{"Author": "William von Hagen", "Title": "Ubuntu Linux Bible"},
"541115":{"Author": "Lohith G.N.", "Title": "Windows Phone 7.5 Application Development with F#"}
]



注意在开头和结尾删除的一对花括号。


Pay attention to the pair of curly braces removed at beginning and end.


这篇关于使用循环遍历JSON而不修改数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆