I am new to javascript and I have a Json Array in a url like below;
[{"year":2015,"month":4,"day":1,"num":0,"time":"2015-04-01","hour":0,"zone":3,"state1":2137,"state2":249,"state3":1810,"state4":30,"state5":0},....]
I want to access the state1 value and assign that value to the variable which I have.How can I do that?(Is parsing necessary or are there any methods there that we can directly access the JSON object in the URL).I am sorry if I asked anything wrong.
You can use jQuery getJSON() function :
$.getJSON(' localhost:8080/dataurl', function(data) {
//data is the JSON string
var jsonObj = JSON.parse(data);
});
Now, Below are the methods to parse the jsonObj to get the state1.
Using array map() method :
var jsonObj = [
{
"year":2015,
"month":4,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2137,
"state2":249,
"state3":1810,
"state4":30,
"state5":0
},
{
"year":2016,
"month":12,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2474,
"state2":250,
"state3":1811,
"state4":31,
"state5":0
}
];
var state1arr = jsonObj.map(function(item) {
return item.state1;
});
console.log(state1arr);
using for...in loop :
var jsonObj = [
{
"year":2015,
"month":4,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2137,
"state2":249,
"state3":1810,
"state4":30,
"state5":0
},
{
"year":2016,
"month":12,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2474,
"state2":250,
"state3":1811,
"state4":31,
"state5":0
}
];
var state1arr = [];
for (var i in jsonObj) {
state1arr.push(jsonObj[i].state1);
}
console.log(state1arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With