Parsing JSON object to get column data
Let's say I have data in a JSON object formatted similarly ...
{"data":
[["X","Y","Z"],
["52","23","10"],
["46","65","32"]]
}
Essentially, each line takes the form [X, Y, Z]
.
What would be the easiest way to access an entire "column" or vector of data? For example, let's say "X", "Y" and "Z" are the title bar and I want to access all of the "X" data.
Do I need to iterate over the entire object in some way to get the first element of each element that will match column "X"?
I would like to do it in JavaScript if possible.
Thanks for the help!
source to share
Try a simple code example that is simple and straightforward to access the first column.
First, iterate over the first row to find the correct column, then get the values โโof that column for the next rows.
<script type="text/javascript">
var obj = {
"data" : [
[ "X", "Y", "Z" ],
[ "52", "23", "10" ],
[ "46", "65", "32" ]
]
};
var column;
for (var i = 0, j = obj.data.length; i < j; i++) {
if (obj.data[0][i] === 'X') {
column = i;
break;
}
}
for (var i = 1, j = obj.data.length; i < j; i++) {
var val = obj.data[i][column];
console.log(val);
}
</script>
source to share
I ran this code for Android. You can try in JavaScript with this type of logic:
String json = "{\"data\":[[\"X\",\"Y\",\"Z\"],[\"52\",\"23\",\"10\"],[\"46\",\"65\",\"32\"]]}";
try {
JSONObject jsonObj = new JSONObject(json);
Log.i(TAG, "DatA : " + jsonObj.getJSONArray("data").length());
JSONArray array = jsonObj.getJSONArray("data");
for(int i=0; i<array.length(); i++) {
Log.i(TAG, "Value : " + array.getJSONArray(i).getString(0));
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Output to Logcat:
12-10 12:26:32.628: I/Demo(28709): DatA : 3 12-10 12:26:32.629: I/Demo(28709): Value : X 12-10 12:26:32.629: I/Demo(28709): Value : 52 12-10 12:26:32.629: I/Demo(28709): Value : 46
Edited: in JavaScript:
<html>
<body>
<p id="demo"></p>
<script>
var text = '{\"data\":[[\"X\",\"Y\",\"Z\"],[\"52\",\"23\",\"10\"],[\"46\",\"65\",\"32\"]]}';
var out = "";
obj = JSON.parse(text);
arr = obj.data;
console.log(arr);
for(i = 0; i < arr.length; i++) {
out += arr[i][0] + "<br>";
}
document.getElementById("demo").innerHTML = out;
</script>
</body>
</html>
source to share
You should try using something like Gson or Jackson Json Processor to process the JSON and deserialize it to something you can use.
How do you do this, you should be able to do something like:
JsonObject json = new JsonParser().parse("...json string...");
JsonArray data = json.get("data");
JsonArray labels = data.getAsJsonArray(0)
for (int i = 1; i < data.size(); i++) {
JsonArray points = data.getAsJsonArray(i);
// do something with: points.getInt(0) -- x column
// do something with: points.getInt(1) -- y column
// do something with: points.getInt(2) -- z column
}
source to share