遍历 JSON 对象:
1. for...in 循环:
var jsonObject = {
"name": "John",
"age": 30,
"city": "New York"
};
for (var key in jsonObject) {
if (jsonObject.hasOwnProperty(key)) {
console.log(key + ": " + jsonObject[key]);
}
}
2. Object.keys() 方法:
var jsonObject = {
"name": "John",
"age": 30,
"city": "New York"
};
Object.keys(jsonObject).forEach(function(key) {
console.log(key + ": " + jsonObject[key]);
});
3. Object.entries() 方法:
var jsonObject = {
"name": "John",
"age": 30,
"city": "New York"
};
Object.entries(jsonObject).forEach(function([key, value]) {
console.log(key + ": " + value);
});
遍历 JSON 数组:
1. for 循环:
var jsonArray = [
{"name": "John", "age": 30, "city": "New York"},
{"name": "Alice", "age": 25, "city": "Los Angeles"},
{"name": "Bob", "age": 35, "city": "Chicago"}
];
for (var i = 0; i < jsonArray.length; i++) {
console.log("Person " + (i + 1) + ":");
var person = jsonArray[i];
for (var key in person) {
if (person.hasOwnProperty(key)) {
console.log(" " + key + ": " + person[key]);
}
}
}
2. forEach 方法:
var jsonArray = [
{"name": "John", "age": 30, "city": "New York"},
{"name": "Alice", "age": 25, "city": "Los Angeles"},
{"name": "Bob", "age": 35, "city": "Chicago"}
];
jsonArray.forEach(function(person, index) {
console.log("Person " + (index + 1) + ":");
Object.entries(person).forEach(function([key, value]) {
console.log(" " + key + ": " + value);
});
});
这些示例提供了一些遍历 JSON 数据的基本方法。根据你的需求和数据结构,选择适合的方法。
转载请注明出处:http://www.zyzy.cn/article/detail/4545/JSON