Javascript how to parse JSON array
Solution 1
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);
}
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).
Solution 2
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);
}
Solution 3
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>
Solution 4
"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.Writer
s 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.
Related videos on Youtube
maephisto
"His code work inspired me to create The Persistence of Memory" - Salvador Dali Full-stack engineer, feeling at home on the web. Interested in image processing, ML and Deep Learning. Contact me via Twitter or mail.
Updated on September 13, 2021Comments
-
maephisto over 2 years
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!
-
T.Todua over 6 yearsPossible duplicate of Safely turning a JSON string into an object
-
-
Bergi about 12 yearsIf he uses a library that supports a cross-browser parseJSON function, he should use that. Also, you repeat the loop mistake.
-
nights over 8 yearsI get an error on the first line when i run this: Uncaught SyntaxError: Unexpected token o
-
musefan over 8 years@nights: That is most likely that you have an invalid JSON string then, try an online JSON validation tool, like this one
-
Tiw about 5 yearsMaybe 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.
-
TsTeaTime about 5 yearsYou 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.
-
Mahdi Jalali about 5 yearsthe 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.