Reputation: 6279
I have JSONArray as below :
[["title","details"],["abc","xyz"],["abc2","xyz2"]]
How to transform into Array of JSONObject as below using Java /JavaScript?
[ { 'title': abc, 'details':xyz,}, {'title': abc2, 'details':xyz2}]
Upvotes: 2
Views: 769
Reputation: 369
Is this what you are looking for ?
jQuery.parseJSON( json ) Returns: Object
Description: Takes a well-formed JSON string and returns the resulting JavaScript object. http://api.jquery.com/jQuery.parseJSON/
Upvotes: 0
Reputation: 17693
Below code was modified from the solution here to allow multiple arrays of values to be passed.
function makeObject(keys, array) {
var output = [];
for (var o = 0; o < array.length; o++) {
var object = {};
for (var i = 0; i < array[o].length; i ++ ) {
object[keys[i]] = array[o][i];
}
output.push(object);
}
return output;
}
// input array
var array = [["title","details"],["abc","xyz"],["abc2","xyz2"]];
// extract keys leaving only values in array
var keys = array.shift();
// build object
var output = makeObject(keys, array);
Example: http://jsfiddle.net/u54tT/1/
Upvotes: 1
Reputation: 6279
I have found a workaround for this for now. Still looking for build in function or concrete implementation on this.
String inputStr = "[[\"title\",\"details\"],[\"abc\",\"xyz\"],[\"abc2\",\"xyz2\"]]";
try {
JSONArray inputArray = new JSONArray(inputStr);
JSONArray outputArray = new JSONArray();
for (int i = 0; i < inputArray.length(); i++) {
JSONArray inArr = inputArray.getJSONArray(i);
for (int j = 0; j < inArr.length(); j++) {
if (i != 0) {
outputArray.put(new JSONObject().put(
inputArray.getJSONArray(0).getString(j), inArr.get(j)));
}
}
}
System.out.println("outputArray = " + outputArray.toString());
} catch (JSONException jse) {
System.out.println("jse = " + jse.toString());
}
Output:
outputArray = [{"title":"abc"},{"details":"xyz"},{"title":"abc2"},{"details":"xyz2"}]
Upvotes: 1
Reputation: 1
If I understood the task correctly there no method that will this job since it seems to be a bit non-trivial case. So you should write your own transformation..
Upvotes: 0