S M Abrar Jahin
S M Abrar Jahin

Reputation: 14578

Convert JSON string with JS

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?

Upvotes: 0

Views: 41

Answers (1)

Magus
Magus

Reputation: 15104

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);

Upvotes: 3

Related Questions