将JSON数组与带有JavaScript的对象一起使用

将JSON数组与带有JavaScript的对象一起使用

本文介绍了将JSON数组与带有JavaScript的对象一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将获取带有对象的JSON数组的函数.在函数中,我将能够遍历数组,访问属性并使用该属性.像这样:

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:

我将传递给该函数的变量如下所示:

Variable that I will pass to the function will look like this:

[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]

function test(myJSON)
{
    // maybe parse my the JSON variable?
    // and then I want to loop through it and access my IDs and my titles
}

有什么建议可以解决吗?

Any suggestions how I can solve it?

推荐答案

这不是一个JSON对象.您有一个JSON对象数组.您需要先遍历数组,然后访问每个对象.以下启动示例可能会有所帮助:

This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:

var arrayOfObjects = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];

for (var i = 0; i < arrayOfObjects.length; i++) {
    var object = arrayOfObjects[i];
    for (var property in object) {
        alert('item ' + i + ': ' + property + '=' + object[property]);
    }
    // If property names are known beforehand, you can also just do e.g.
    // alert(object.id + ',' + object.Title);
}

要了解有关JSON的更多信息,请查看本文.

To learn more about JSON, check this article.

更新:如果JSON对象数组实际上是作为普通香草字符串传递的,那么您确实需要在这里eval().

Update: if the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.

var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...

这篇关于将JSON数组与带有JavaScript的对象一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:22