0

I have a JS string like this (got from AJAX API call)

  {"Task":"Hours per Day","Slep":22,"Work":25,"Watch TV":15,"Commute":4,"Eat":7,"Bathroom":17}

I want to convert it into this format-

  [["Task", "Hours per Day"], ["Work", 11], ["Eat", 2], ["Commute", 2], ["Watch TV", 2], ["Sleep", 7]]

With the help of JS and jQuery.

Is there any way?

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
  • Already answered - http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object?rq=1 – Bala.Raj Sep 29 '15 at 14:21
  • Does this answer your question? [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Brian Tompsett - 汤莱恩 Jul 08 '20 at 14:00

1 Answers1

3

You can do like this :

// Parse your string into an object
var obj = JSON.parse(json); 

var array = [];

// Iterate on your object keys
for (var key in obj) {
    array.push([key, obj[key]]);
}

// Convert array into a JSON
json = JSON.stringify(array);

If you want to support old browsers, the for (var key in obj) may not work. You can also do like this if you want :

// Parse your string into an object
var obj = JSON.parse(json);

var array = [],
    keys = Object.keys(obj);

// Iterate on your object keys
for (var i = 0; i < keys.length; ++i) {
    var key = keys[i];
    array.push([key, obj[key]]);
}

// Convert array into a JSON
json = JSON.stringify(array);
Magus
  • 14,796
  • 3
  • 36
  • 51