如何循环JSON对象?

时间:2017-06-13 06:33:58

标签: json

我们如何遍历给定的JSON对象来遍历其所有属性:

<script type="text/javascript">
var students =  '{"name": "John", "age": 30, "subjects": [{ "name": "IT", "marks": 85 }, { "name": "Maths", "marks": 75 }, { "name": "English", "marks": 60 }]}';

var myObj = JSON.parse(students);
alert(myObj.name);                  
alert(myObj.age);                   
alert(myObj.subjects[0]['name']);                   
alert(myObj.subjects[0]['marks']);                  
alert(myObj.subjects[1]['name']);                   
alert(myObj.subjects[1]['marks']);                  
alert(myObj.subjects[2]['name']);                   
alert(myObj.subjects[2]['marks']);                  
</script>

您可以通过使用其索引和属性名称来查看我正在访问嵌套的“主题”属性。但代码变得冗长,以遍历每个项目。为了避免它,我想知道如何通过编写单行代码来访问它的所有属性来循环(例如for循环)?

3 个答案:

答案 0 :(得分:3)

你可以这样做:

var myObj = JSON.parse(students);
for(var index = 0; index < myObj.subjects.length; index++) {                 
  alert(myObj.subjects[index]['name']);                   
  alert(myObj.subjects[index]['marks']);                  
}

答案 1 :(得分:1)

只需使用Each函数迭代每个主题

&#13;
&#13;
var students =  '{"name": "John", "age": 30, "subjects": [{ "name": "IT", "marks": 85 }, { "name": "Maths", "marks": 75 }, { "name": "English", "marks": 60 }]}';

var myObj = JSON.parse(students);


$.each(myObj['subjects'], function(index, value) {
    console.log(value['name']+" "+ value['marks']);
    
});
 
 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试使用stringify

sort file1|uniq -u