简体   繁体   English

如何获取具有以下格式的json数据?

[英]how to get json data with the following format?

I've a json file to get a list of test results. 我有一个json文件来获取测试结果列表。 Below is the json file. 以下是json文件。 And a short snippet of the jquery. 还有一小段jquery。 I am trying to get the test id from the json and display them as a unordered list. 我试图从json获取测试ID,并将其显示为无序列表。 How can I do that? 我怎样才能做到这一点?

[
         {
               "Test":{
               "id":"2949",
               "bk_session_id":"qpmz3gd6xw",
               "series_type":"Cars Series",
               "book_type":"A",
               }
         },
         {
               "Test":{
               "id":"2950",
               "bk_session_id":"qpmz3gd6xw",
               "series_type":"Cars Series",
               "book_type":"A",
               }
         }
]


<script type="text/javascript">

     $.getJSON("http://localhost:8888/tests/students.json?id=qpmz3gd6xw", function(data) {
     for (var i in data) 
        {
            alert(data[i].[Test].id);
        }
     }); 

</script>

You're missing the quotes around Test , it should be a string and remove the dot before it. 您缺少Test周围的引号,它应该是一个字符串,并删除其前的点。

alert(data[i]['Test'].id);

also your json is not valid, remove the trailing , after each book_type. 另外您的json无效,在每个book_type之后删除结尾的。

[
         {
               "Test":{
               "id":"2949",
               "bk_session_id":"qpmz3gd6xw",
               "series_type":"Cars Series",
               "book_type":"A"
               }
         },
         {
               "Test":{
               "id":"2950",
               "bk_session_id":"qpmz3gd6xw",
               "series_type":"Cars Series",
               "book_type":"A"
               }
         }
]

http://jsfiddle.net/ef7Nq/ http://jsfiddle.net/ef7Nq/

Try 尝试

Fiddle Demo 小提琴演示

var ul = '';
for (var i in data) 
{
    ul += '<li>'+data[i]['Test'].id+'</li>';
}
$('#el').append($('<ul/>').html(ul));

Loop through the items in the array and append nodes for each id. 循环遍历数组中的项目,并为每个id附加节点。

$.each(obj, function (i, item) {
    ul.append($('<li>' + item.Test.id + '</li>'));
});

fiddle here 在这里摆弄

您可以执行data[i]['Test'].iddata[i].Test.id因为名称中没有空格。

You can try this: 您可以尝试以下方法:

alert( data[i].Test.id );

Full Code: 完整代码:

$.getJSON("http://localhost:8888/tests/students.json?id=qpmz3gd6xw", function(data) {
     for (var i in data) {
            alert( data[i].Test.id );
     }
});

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM