简体   繁体   中英

Change json array format for highcharts

I am using JSONArray and JSONObject in a @RestController class in Java to generate a json array for highcharts.

The output is in this format: [{"17":183},{"16":185},{"15":178},{"14":241},{"13":326},{"12":193},{"11":175},{"10":132},{"9":42},{"4":12},{"3":306},{"2":362},{"1":382},{"0":305}]

I need to change it to this format: [[1,12],[2,5],[3,18],[4,13],[5,7],[6,4],[7,9],[8,10],[9,15],[10,22],[11,23],[12,13],[13,14],[14,23]]

Is this doable using JSONArray and JSONObject? or what other solutions do I have?

You need to use inner arrays instead of objects. For example:

JsonArray result = Json.createArrayBuilder()
                       .add(Json.createArrayBuilder().add(1).add(12))
                       .add(Json.createArrayBuilder().add(2).add(5))
                       .build();

As the other solution, you can parse that data in JS:

var parsedData = [];
$.each(json_data, function (key, val) {
  parsedData.push([parseInt(key, 10), val]);
});

And data must be sorted ascending by x-values, so it may be necessary to sort data manually too:

parsedData.sort(function (a, b) {
  return a[0] - b[0];
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM