120

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!

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
maephisto
  • 4,952
  • 11
  • 53
  • 73
  • 1
    Possible duplicate of [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – T.Todua Nov 30 '17 at 14:33

9 Answers9

171

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

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

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

musefan
  • 47,875
  • 21
  • 135
  • 185
  • 1
    If he uses a library that supports a cross-browser parseJSON function, he should use that. Also, you repeat the loop mistake. – Bergi Apr 03 '12 at 11:05
  • I get an error on the first line when i run this: Uncaught SyntaxError: Unexpected token o – nights Nov 19 '15 at 03:23
  • @nights: That is most likely that you have an invalid JSON string then, try an online JSON validation tool, [like this one](http://jsonlint.com/) – musefan Nov 19 '15 at 09:58
8

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>
hurikhan77
  • 5,881
  • 3
  • 32
  • 47
Fisher Man
  • 487
  • 1
  • 5
  • 14
8

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);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

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://learn.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript

hB0
  • 1,977
  • 1
  • 27
  • 33
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.

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.

rzen
  • 31
  • 4
0

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);
}
ElChiniNet
  • 2,778
  • 2
  • 19
  • 27
Sobhit Sharma
  • 697
  • 14
  • 45
0

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);
}
Mahdi Jalali
  • 323
  • 3
  • 3
  • 1
    Maybe you mean *can* where you said *should*. However it's better if you add more details / explanations to your code, that will better help OP and other people who has same question. – Til May 05 '19 at 12:12
  • You can also explain a little on why you chose this method so that the user learns a bit more. That would help improve this answer. – TsTeaTime May 05 '19 at 12:37
  • the answer with the most vote answered this question but when I use it understood it's wrong in line 4 : var counter = jsonData.counters[i]; But I change it to : var counter = jsonData[i].counters; and it worked. so I said can instead of should. – Mahdi Jalali May 06 '19 at 06:38
-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.

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()+"]")
James Wolfe
  • 340
  • 5
  • 18
-1

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.

Geerten
  • 1,027
  • 1
  • 9
  • 22