Javascript如何解析JSON数组

时间:2021-11-25 21:30:20

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!

我做错了什么?谢谢你!

7 个解决方案

#1


95  

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)。使用forin循环将把var设置为当前循环的属性名,而不是实际的数据。查看我的更新循环,以正确使用。

IMPORTANT: the JSON.parse method 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。解析方法在旧的浏览器中不能工作-所以如果你计划通过某种时间弯曲互联网连接使你的网站可用,这可能是一个问题!如果你真的感兴趣,这里有一个支持图表(它勾起了我所有的方框)。

#2


4  

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

在forin -loop中,运行的变量包含属性名,而不是属性值。

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:

但是由于计数器是数组,所以必须使用普通的for循环:

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

#3


2  

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>

#4


1  

"Sencha way" for interacting with server data is setting up an Ext.data.Store proxied 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。通过Ext.data.proxy对存储进行代理。Proxy(在本例中是Ext.data.proxy.Ajax)具有Ext.data.reader。Json(对于Json编码的数据,也有其他读取器可用)。对于将数据写入服务器,有一个Ext.data.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.json in 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(在这个小提琴中也有)包含了您的数据。idProperty: 'counter_name'在本例中可能是可选的,但通常指向主键属性。rootProperty:“计数器”指定哪些属性包含数据项数组。

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触摸适当的UI组件,如网格、列表或表单。

#5


0  

You should use a datastore and proxy in ExtJs. There are plenty of examples of 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相同的核心函数。

#6


0  

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

#7


-1  

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()+"]")

#1


95  

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)。使用forin循环将把var设置为当前循环的属性名,而不是实际的数据。查看我的更新循环,以正确使用。

IMPORTANT: the JSON.parse method 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。解析方法在旧的浏览器中不能工作-所以如果你计划通过某种时间弯曲互联网连接使你的网站可用,这可能是一个问题!如果你真的感兴趣,这里有一个支持图表(它勾起了我所有的方框)。

#2


4  

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

在forin -loop中,运行的变量包含属性名,而不是属性值。

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:

但是由于计数器是数组,所以必须使用普通的for循环:

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

#3


2  

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>

#4


1  

"Sencha way" for interacting with server data is setting up an Ext.data.Store proxied 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。通过Ext.data.proxy对存储进行代理。Proxy(在本例中是Ext.data.proxy.Ajax)具有Ext.data.reader。Json(对于Json编码的数据,也有其他读取器可用)。对于将数据写入服务器,有一个Ext.data.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.json in 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(在这个小提琴中也有)包含了您的数据。idProperty: 'counter_name'在本例中可能是可选的,但通常指向主键属性。rootProperty:“计数器”指定哪些属性包含数据项数组。

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触摸适当的UI组件,如网格、列表或表单。

#5


0  

You should use a datastore and proxy in ExtJs. There are plenty of examples of 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相同的核心函数。

#6


0  

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

#7


-1  

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()+"]")