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?

2

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.