js json遍历
时间: 2023-08-06 08:01:43 浏览: 91
可以使用JavaScript的for...in循环来遍历JSON对象,示例如下:
```javascript
const json = {
"name": "John",
"age": 30,
"city": "New York"
}
for (let key in json) {
console.log(key + ": " + json[key]);
}
```
输出结果为:
```
name: John
age: 30
city: New York
```
如果JSON对象中嵌套了其他JSON对象或数组,可以使用递归来进行遍历,示例如下:
```javascript
const json = {
"name": "John",
"age": 30,
"city": "New York",
"skills": {
"programming": ["JavaScript", "Python", "Java"],
"language": ["English", "Spanish"]
}
}
function traverseJSON(obj) {
for (let key in obj) {
if (typeof obj[key] === "object") {
traverseJSON(obj[key]);
} else {
console.log(key + ": " + obj[key]);
}
}
}
traverseJSON(json);
```
输出结果为:
```
name: John
age: 30
city: New York
programming: JavaScript,Python,Java
language: English,Spanish
```
阅读全文