Javascript 如何解析 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9991805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:05:46  来源:igfitidea点击:

Javascript how to parse JSON array

javascriptjsonextjs

提问by maephisto

I'm using Sencha Touch (ExtJS) to get a JSON message from the server. The message I receive is this one :

我正在使用 Sencha Touch (ExtJS) 从服务器获取 JSON 消息。我收到的消息是这样的:

{
"success": true,
"counters": [
    {
        "counter_name": "dsd",
        "counter_type": "sds",
        "counter_unit": "sds"
    },
    {
        "counter_name": "gdg",
        "counter_type": "dfd",
        "counter_unit": "ds"
    },
    {
        "counter_name": "sdsData",
        "counter_type": "sds",
        "counter_unit": "   dd       "
    },
    {
        "counter_name": "Stoc final",
        "counter_type": "number    ",
        "counter_unit": "litri     "
    },
    {
        "counter_name": "Consum GPL",
        "counter_type": "number    ",
        "counter_unit": "litri     "
    },
    {
        "counter_name": "sdg",
        "counter_type": "dfg",
        "counter_unit": "gfgd"
    },
    {
        "counter_name": "dfgd",
        "counter_type": "fgf",
        "counter_unit": "liggtggggri     "
    },
    {
        "counter_name": "fgd",
        "counter_type": "dfg",
        "counter_unit": "kwfgf       "
    },
    {
        "counter_name": "dfg",
        "counter_type": "dfg",
        "counter_unit": "dg"
    },
    {
        "counter_name": "gd",
        "counter_type": "dfg",
        "counter_unit": "dfg"
    }

    ]
}

My problem is that I can't parse this JSON object so that i can use each of the counter objects.

我的问题是我无法解析这个 JSON 对象,所以我可以使用每个计数器对象。

I'm trying to acomplish that like this :

我正在尝试像这样完成:

var jsonData = Ext.util.JSON.decode(myMessage);
for (var counter in jsonData.counters) {
     console.log(counter.counter_name);
 }

What am i doing wrong ? Thank you!

我究竟做错了什么 ?谢谢!

回答by musefan

Javascript has a built in JSON parse for strings, which I think is what you have:

Javascript 有一个内置的字符串 JSON 解析,我认为这就是你所拥有的:

var myObject = JSON.parse("my json string");

to use this with your example would be:

将此与您的示例一起使用将是:

var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
    var counter = jsonData.counters[i];
    console.log(counter.counter_name);
}

Here is a working example

这是一个工作示例

EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to @Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage

编辑:您在使用 for 循环时有一个错误(我在第一次阅读时错过了这个,当场归功于 @Evert)。使用 for-in 循环会将 var 设置为当前循环的属性名称,而不是实际数据。请参阅上面我更新的循环以正确使用

IMPORTANT: the JSON.parsemethod wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart(which ticks all my boxes).

重要提示:该JSON.parse方法在旧的旧浏览器中不起作用 - 因此,如果您打算通过某种时间弯曲互联网连接使您的网站可用,这可能是一个问题!如果你真的有兴趣,这里有一个支持图表(它勾选了我所有的方框)。

回答by Fisher Man

This is my answer,

这是我的回答,

<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br> 
Last Name: <span id="lname"></span><br> 
</p> 
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
    var counter = jsonData.employees[i];
    //console.log(counter.counter_name);
    alert(counter.firstName);
}

</script>
</body>
</html>

回答by Bergi

In a for-in-loop the running variable holds the property name, not the property value.

在 for 循环中,运行变量保存属性名称,而不是属性值。

for (var counter in jsonData.counters) {
    console.log(jsonData.counters[counter].counter_name);
}

But as counters is an Array, you have to use a normal for-loop:

但由于 counters 是一个数组,你必须使用普通的 for 循环:

for (var i=0; i<jsonData.counters.length; i++) {
    var counter = jsonData.counters[i];
    console.log(counter.counter_name);
}

回答by rzen

"Sencha way" for interacting with server data is setting up an Ext.data.Storeproxied by a Ext.data.proxy.Proxy(in this case Ext.data.proxy.Ajax) furnished with a Ext.data.reader.Json(for JSON-encoded data, there are other readers available as well). For writing data back to the server there's a Ext.data.writer.Writers of several kinds.

与服务器数据交互的“Sencha 方式”是设置一个Ext.data.Store代理Ext.data.proxy.Proxy(在本例中Ext.data.proxy.Ajax),并配备了一个Ext.data.reader.Json(对于 JSON 编码的数据,还有其他阅读器可用)。为了将数据写回服务器,有Ext.data.writer.Writer几种类型。

Here's an example of a setup like that:

这是这样的设置示例:

    var store = Ext.create('Ext.data.Store', {
        fields: [
            'counter_name',
            'counter_type',
            'counter_unit'
        ],

        proxy: {
            type: 'ajax',
            url: 'data1.json',

            reader: {
                type: 'json',
                idProperty: 'counter_name',
                rootProperty: 'counters'
            }
        }
    });

data1.jsonin this example (also available in this fiddle) contains your data verbatim. idProperty: 'counter_name'is probably optional in this case but usually points at primary key attribute. rootProperty: 'counters'specifies which property contains array of data items.

data1.json在这个例子中(也可以在这个 fiddle 中找到)包含你的数据。idProperty: 'counter_name'在这种情况下可能是可选的,但通常指向主键属性。rootProperty: 'counters'指定哪个属性包含数据项数组。

With a store setup this way you can re-read data from the server by calling store.load(). You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.

通过这种方式设置存储,您可以通过调用从服务器重新读取数据store.load()。您还可以将商店连接到任何适合 Sencha Touch 的 UI 组件,如网格、列表或表单。

回答by Sobhit Sharma

This works like charm!

这就像魅力一样!

So I edited the code as per my requirement. And here are the changes: It will save the id number from the response into the environment variable.

所以我根据我的要求编辑了代码。以下是更改:它将响应中的 id 号保存到环境变量中。

var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++)
{
    var counter = jsonData.data[i];
    postman.setEnvironmentVariable("schID", counter.id);
}

回答by Mahdi Jalali

The answer with the higher vote has a mistake. when I used it I find out it in line 3 :

得票高的答案有误。当我使用它时,我在第 3 行发现它:

var counter = jsonData.counters[i];

I changed it to :

我把它改成:

var counter = jsonData[i].counters;

and it worked for me. There is a difference to the other answers in line 3:

它对我有用。与第 3 行中的其他答案有所不同:

var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
    var counter = jsonData[i].counters;
    console.log(counter.counter_name);
}

回答by Drew

Just as a heads up...

就像一个抬头...

var data = JSON.parse(responseBody);

has been deprecated.

已被弃用

Postman Learning Center nowsuggests

邮递员学习中心现在建议

var jsonData = pm.response.json();

回答by hB0

Something more to the point for me..

对我来说更重要的事情..

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';  
var contact = JSON.parse(jsontext);  
document.write(contact.surname + ", " + contact.firstname);  
document.write(contact.phone[1]);  
// Output:  
// Aaberg, Jesper  
// 555-0100

Reference: https://docs.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript

参考:https: //docs.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript

回答by Geerten

You should use a datastore and proxy in ExtJs. There are plenty of examplesof this, and the JSON reader automatically parses the JSON message into the model you specified.

您应该在 ExtJs 中使用数据存储和代理。有很多这样的例子,JSON 阅读器会自动将 JSON 消息解析为您指定的模型。

There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.

使用 ExtJs 时不需要使用基本的 Javascript,一切都不同,您应该使用 ExtJs 的方式来使一切正确。仔细阅读那里的文档,很好。

By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.

顺便说一句,这些示例也适用于 Sencha Touch(尤其是 v2),它基于与 ExtJs 相同的核心功能。

回答by James Wolfe

Not sure if my data matched exactly but I had an array of arrays of JSON objects, that got exported from jQuery FormBuilder when using pages.

不确定我的数据是否完全匹配,但我有一组 JSON 对象数组,在使用页面时从 jQuery FormBuilder 导出。

Hopefully my answer can help anyone who stumbles onto this question looking for an answer to a problem similar to what I had.

希望我的回答可以帮助任何偶然发现这个问题的人,他们正在寻找与我遇到的问题类似的问题的答案。

The data looked somewhat like this:

数据看起来有点像这样:

var allData = 
[
    [
        {
            "type":"text",
            "label":"Text Field"
        }, 
        {
            "type":"text",
            "label":"Text Field"
        }
    ],
    [
        {
            "type":"text",
            "label":"Text Field"
        }, 
        {
            "type":"text",
            "label":"Text Field"
        }
    ]
]

What I did to parse this was to simply do the following:

我所做的解析这个只是简单地执行以下操作:

JSON.parse("["+allData.toString()+"]")