Reputation: 387
I'm new in using JSON and I have trouble extracting data from a parsed JSON object :
I have a getstats.php file that echoes a json encoded result from a mysql query. Here is an example of what the php file returns :
[{"x":"0","label":"July","y":"23"},{"x":"1","label":"August","y":"58"},{"x":"2","label":"September","y":"78"},{"x":"3","label":"October","y":"77"}]
This is caught by an ajax query in a separate javascript file :
$.ajax({
type: "POST",
url: "getstats.php",
dataType: "json",
data: {start : start, end : end},
success: function(data) {
//here I deal with the JSON
}
});
So far so good, I can access each values individually (data[2].month == 'September'
...)
I want to split the variable data
so I can use the values into a flot chart, so I need something like :
var dataset = [[0,23],[1,58],[2,78],[3,77]];
var xlabel = [[0,'July'],[1,'August'],[2,'September'],[3,'October']];
I can't figure out an easy way to do this (I mean without doing a loop through data
and extracting the values into new arrays one by one).
Upvotes: 1
Views: 1988
Reputation: 2718
Unless you restructure you JSON to represent the two arrays I don't see a different way. Whether you loop yourself or use a helper method from some library or your own code it will have to be traversed.
So that being said your data JSON could have two properties called PropA
and PropB
and those two properties would have exactly what you need for your dataset
and xlabel
arrays. So instead of looping through data you would just do:
dataset = data.PropA
xlabel= data.PropB
Upvotes: 1