简体   繁体   English

Javascript 如何解析 JSON 数组

[英]Javascript how to parse JSON array

I'm using Sencha Touch (ExtJS) to get a JSON message from the server.我正在使用 Sencha Touch (ExtJS) 从服务器获取 JSON 消息。 The message I receive is this one :我收到的消息是这样的:

{
"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!谢谢!

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).编辑:您在使用 for 循环时有一个错误(我在第一次阅读时错过了这个,当场归功于 @Evert)。 using a for-in loop will set the var to be the property name of the current loop, not the actual data.使用 for-in 循环会将 var 设置为当前循环的属性名称,而不是实际数据。 See my updated loop above for correct usage请参阅上面我更新的循环以正确使用

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!重要提示JSON.parse方法在旧的旧浏览器中不起作用 - 因此,如果您打算通过某种时间弯曲互联网连接使您的网站可用,这可能是一个问题! If you really are interested though, here is a support chart (which ticks all my boxes).如果你真的有兴趣,这里有一个支持图表(它勾选了我所有的框)。

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>

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);
}

"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).与服务器数据交互的“Sencha 方式”是设置一个Ext.data.Store代理的Ext.data.proxy.Proxy (在本例中为Ext.data.proxy.Ajax )配备有Ext.data.reader.Json (对于 JSON 编码的数据,还有其他阅读器可用)。 For writing data back to the server there's a Ext.data.writer.Writer s of several kinds.为了将数据写回服务器,有几种类型的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.json in this example (also available in this fiddle ) contains your data verbatim.本示例中的data1.json (也可在此 fiddle 中使用)包含您的数据逐字记录。 idProperty: 'counter_name' is probably optional in this case but usually points at primary key attribute. idProperty: 'counter_name'在这种情况下可能是可选的,但通常指向主键属性。 rootProperty: 'counters' specifies which property contains array of data items. rootProperty: 'counters'指定哪个属性包含数据项数组。

With a store setup this way you can re-read data from the server by calling store.load() .通过这种方式设置存储,您可以通过调用store.load()从服务器重新读取数据。 You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.您还可以将商店连接到任何适合 Sencha Touch 的 UI 组件,如网格、列表或表单。

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

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);
}

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);
}

Just as a heads up...就像一个抬头...

var data = JSON.parse(responseBody);

has been deprecated .已被弃用

Postman Learning Center now suggests邮递员学习中心现在建议

var jsonData = pm.response.json();

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

You should use a datastore and proxy in ExtJs.您应该在 ExtJs 中使用数据存储和代理。 There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.有很多这样的 例子,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.使用 ExtJs 时不需要使用基本的 Javascript,一切都不同,您应该使用 ExtJs 的方式来使一切正确。 Read there documentation carefully, it's good.仔细阅读那里的文档,很好。

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 相同的核心功能。

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

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