Scobal Scobal - 16 days ago 9
Java Question

Convert JSON structure

I have a set of data in one JSON structure:

[[task1, 10, 99],
[task2, 10, 99],
[task3, 10, 99],
[task1, 11, 99],
[task2, 11, 99],
[task3, 11, 99]]


and need to convert it to another JSON structure:

[{
label: "task1",
data: [[10, 99], [11, 99]]
},
{
label: "task2",
data: [[10, 99], [11, 99]]
},
{
label: "task3",
data: [[10, 99], [11, 99]]
}]


What's the best way to do this with javascript/java?

Answer

For Java you can use json-simple from JSON.org. I don't think there's a 'clever' way to do it, as others have said, you just have to convert the JSON to real objects, manipulate and convert back. (see below) Also I believe that you have to quote literal strings, eg. "task1", "label", "data" for it to be valid JSON (or at least, json-simple won't accept it if you don't)

    package com.another;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class NewClass {

    public static final String inputString = "[ [\"task1\", 10, 99],   [\"task2\", 10, 99],   [\"task3\", 10, 99],   [\"task1\", 11, 99],   [\"task2\", 11, 99],   [\"task3\", 11, 99]]";

    public static void main(String[] args) throws ParseException {
        JSONArray obj = (JSONArray) new JSONParser().parse(inputString);
        Map<Object, JSONObject> output = new HashMap<Object, JSONObject>();
        for (Object o : obj) {
            JSONArray item = (JSONArray) o;
            Object title = item.get(0);
            Object first = item.get(1);
            Object second = item.get(2);
            JSONObject dest = output.get(title);
            if (dest == null) {
                dest = new JSONObject();
                output.put(title, dest);
                dest.put("label", title);
                dest.put("data", new JSONArray());
            }
            JSONArray data = new JSONArray();
            data.add(first);
            data.add(second);
            ((JSONArray) dest.get("data")).add(data);
        }
        String outputString = JSONArray.toJSONString(Arrays.asList(output.values().toArray()));
        System.out.println(outputString);
    }
}

Here it is in JS

var inputString = "[ [\"task1\", 10, 99],   [\"task2\", 10, 99],   [\"task3\", 10, 99],   [\"task1\", 11, 99],   [\"task2\", 11, 99],   [\"task3\", 11, 99]]";

var obj = JSON.parse(inputString);
var output = new Object();
for (var i in obj) {
    var item = obj[i];
    var title = item[0];
    var first = item[1];
    var second = item[2];
    var dest = output[title];
    if (dest == null) {
        dest = {
            "label" : title,
            "data": new Array()
            };
        output[title] = dest;
    }
    dest.data.push([first, second]);
}
var outputArray = new Array();
for (var t in output) {
    outputArray.push(output[t]);
}