[javascript] Javascript how to parse JSON array

I'm using Sencha Touch (ExtJS) to get a JSON message from the server. 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.

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!

This question is related to javascript json extjs

The answer is


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


Just as a heads up...

var data = JSON.parse(responseBody);

has been deprecated.

Postman Learning Center now suggests

var jsonData = pm.response.json();

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

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 (var i=0; i<jsonData.counters.length; i++) {
    var counter = jsonData.counters[i];
    console.log(counter.counter_name);
}

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>

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.

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

"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.

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.

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.


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.

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.

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


The answer with the higher vote has a mistake. when I used it I find out it in line 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:

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

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.

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to extjs

How can I let a user download multiple files when a button is clicked? How to display binary data as image - extjs 4 Javascript how to parse JSON array How to retrieve Request Payload How to stop a setTimeout loop? Explain ExtJS 4 event handling ExtJs Gridpanel store refresh How to retrieve JSON Data Array from ExtJS Store What are alternatives to ExtJS?