137

I need to convert JSON object string to a JavaScript array.

This my JSON object:

{"2013-01-21":1,"2013-01-22":7}

And I want to have:

var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');

data.addRows([
    ['2013-01-21', 1],
    ['2013-01-22', 7]
]);

How can I achieve this?

simhumileco
  • 31,877
  • 16
  • 137
  • 115
user1960311
  • 1,369
  • 2
  • 9
  • 6

11 Answers11

128
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];

for(var i in json_data)
    result.push([i, json_data [i]]);


var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);

http://jsfiddle.net/MV5rj/

salexch
  • 2,644
  • 1
  • 20
  • 17
99

If you have a well-formed JSON string, you should be able to do

var as = JSON.parse(jstring);

I do this all the time when transfering arrays through AJAX.

aggaton
  • 3,066
  • 2
  • 25
  • 36
65

Suppose you have:

var j = {0: "1", 1: "2", 2: "3", 3: "4"};

You could get the values with (supported in practically all browser versions):

Object.keys(j).map(function(_) { return j[_]; })

or simply:

Object.values(j)

Output:

["1", "2", "3", "4"]
mvallebr
  • 2,388
  • 21
  • 36
  • 10
    Whoever reads this... Use [Object.values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) instead! – Nico Van Belle Dec 05 '19 at 08:00
  • 1
    Just remember that Object.values() isn't [supported on any version of IE](https://caniuse.com/?search=Object.values) – A Friend Nov 20 '20 at 22:53
  • 9
    IE doesn't support _anything_. Does it really matter what is and isn't compatible with it? – Someone Apr 29 '21 at 16:56
  • @Someone if MS doesn't support IE, why should any of the rest of us? Just pretend it was all a bad dream... – WinEunuuchs2Unix Jan 25 '22 at 00:45
29
function json2array(json){
    var result = [];
    var keys = Object.keys(json);
    keys.forEach(function(key){
        result.push(json[key]);
    });
    return result;
}

See this complete explanation: http://book.mixu.net/node/ch5.html

Roger Garzon Nieto
  • 6,554
  • 2
  • 28
  • 24
25

This will solve the problem:

const json_data = {"2013-01-21":1,"2013-01-22":7};

const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);

console.log(arr);

Or using Object.entries() method:

console.log(Object.entries(json_data));

In both the cases, output will be:

/* output: 
[['2013-01-21', 1], ['2013-01-22', 7]]
*/

The above solutions do not work for nested objects. For nested objects, we can do something like this:

const isObject = (obj) => {
  return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
}

const objToArray = (obj) => {
  return Object.keys(obj).map((key) => {
    return [
      key, isObject(obj[key]) ? 
        objToArray(obj[key]) :
        obj[key]
    ];
  });    
}

const json_data = {
  "2013-01-21":1, 
  "2013-01-22":7,
  "ab":{"x":{"xa": 3, "xb": 4}, "y": 2},
};

console.log(JSON.stringify(objToArray(json_data)));

The output in this case will be:

/* output: 
[["2013-01-21",1],["2013-01-22",7],["ab",[["x",[["xa",3],["xb",4]]],["y",2]]]]
*/
Rakesh Sharma
  • 608
  • 6
  • 9
  • Great. but doesn't work for nested objects. var data = {"2013-01-21":1,"2013-01-22":7, "ab":{"x":1}}; returns [["2013-01-21",1],["2013-01-22",7],["ab",{"x":1}]] – MPV May 15 '21 at 18:20
  • Edited the solution for nested objects with DFS approach. – Rakesh Sharma May 14 '22 at 09:57
8

You can insert object items to an array as this

 
 let obj2 = {"2013-01-21":1,"2013-01-22":7}
 
 console.log(Object.keys(obj2).map(key => [key, obj2[key]]))

let obj = {
  '1st': {
    name: 'stackoverflow'
  },
  '2nd': {
    name: 'stackexchange'
  }
};

// you can use Object.values(obj)
console.log(Object.values(obj))
 
// or you can use this instead. 
 let wholeArray = Object.keys(obj).map(key => obj[key]);

 
 console.log(wholeArray);
 console.log(Object.values(obj));
noone
  • 6,168
  • 2
  • 42
  • 51
  • 1
    This is not the same json structure as the question. This will not work correctly with key/value pairs. It will only return an array of values. – Dylan Prem Mar 07 '22 at 20:29
  • 1
    @DylanPrem Thankyou for pointing out. Maybe the author edited the question. But anyway, fixed the answer. – noone Mar 08 '22 at 15:16
3

Consider having a json object we want to convert

const my_object = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

There is several solution you can use :

1. Object.keys() and Object.values()

Theses functions convert any object to an array. One returns an array with all the keys, and the other all the values :

console.log(Object.keys(my_object))
// Output : ["key1", "key2", "key3"]

console.log(Object.values(my_object))
// Output : ["value1", "value2", "value3"]

I'm not sure to understand the initial question, but the solution would probably be

data.addRows(Object.values(my_object));

2. Object.entries()

This function is a mix of the two above:

console.log(Object.entries(my_object))
// Output : [["key1", "value1"],  ["key2", "value2"],  ["key3", "value3"]]

It no use for the initial question, but this function is so usefull I had to mention it. Especially, when the value_ are nested object. Let say our values are objects like this :

const my_object = {
    "key1": {"a": 1, "b": 2},
    "key2": {"y": 25, "z": 26},
    "key3": {"much": "stuff"}
}

and we want to end up with an array like this

my_array = [
    {"key": "key1", "a": 1, "b": 2},
    {"key": "key2", "y": 25, "z": 26},
    {"key": "key3", "much": "stuff"}
]

We need to use Object.entries() to get all our key with their value. We will start with an overdetailed code :

my_array = Object.entries(my_object).map(function(entry){
   key = entry[0];
   value = entry[1];

   nested_object = value;
   nested_object.key = key;

   return nested_object;
});

console.log(my_array);
// Expected output : [
//    {"key": "key1", "a": 1, "b": 2},
//    {"key": "key2", "y": 25, "z": 26},
//    {"key": "key3", "much": "stuff"}
//]

We can make use of spread operator to simplify our code :

my_array = Object.entries(my_object).map(entry => {"key": entry[0], ...entry[1]});

console.log(my_array);
// Expected output : [
//    {"key": "key1", "a": 1, "b": 2},
//    {"key": "key2", "y": 25, "z": 26},
//    {"key": "key3", "much": "stuff"}
//]
Portevent
  • 714
  • 3
  • 12
  • 34
  • There is no such thing as a _"JSON object"_ or _"JSON array"_. [JSON](https://json.org) is a text representation of some data structure (usually an object or an array but any data type can be encoded as JSON). Because JSON is text and nothing more, in order to process it, one has to decode it back into data structures equivalent to those used to create the JSON. In your example, `json_object` is a JavaScript object (and the quotes around the keys are not needed) and `json_array` is a JavaScript array. There is no trace of JSON in this response. – axiac Nov 16 '21 at 15:07
  • Yes of course. I'm thinking `json_object` as the object from my json. But i'll rename them to avoid further confusions – Portevent Nov 16 '21 at 15:35
3

if the goal is to create an array of objects, here is a solution that will accomplish what you're trying to do using Object.keys():

const jsonResponse = '{"2013-01-21":1,"2013-01-22":7}'
// Only use json parse if the data is a JSON string.
const obj = typeof jsonResponse === 'string' ? JSON.parse(jsonResponse) : jsonResponse;
const data = [];

Object.keys(obj).forEach((key) => data.push({[key]: obj[key]}))
// Example 2 - storing it directly in a variable using map
const arrayOfObjs = Object.keys(obj).map((key) => ({[key]: obj[key]}))

Or using Object.entries()

// Example 1
Object.entries(obj).forEach((array) => data.push({[array[0]]: array[1]}))
// Example 2
Object.entries(obj).forEach(([key, value]) => data.push({[key]: value}))
// Example 3 - Store it directly in a new variable using map
const arrayOfObjs = Object.entries(obj).map(([key, value]) => ({[key]: value}))
Dylan Prem
  • 174
  • 11
2

Some correction to @Mister Aqua's SOLUTION

const my_array = [];
    Object.entries(set_of_objects).map(function (entry) {
      const key = entry[0];
      const value = entry[1];

      const nested_object = {};

      nested_object[key] = value;
      my_array.push(nested_object);
    });

Chill Pill :)

Ali Akram
  • 4,803
  • 3
  • 29
  • 38
1

i got this error when i put my long JSON string in a hidden div and then tried to convert it to JSON by this code-

var data = document.getElementById('data');
var json = JSON.parse(data);

spotted error yet? yes, i forgot to add .innerHTML in first line. so data is already an object. not a string. how can a object be parsed by JSON.parse?

JSON.parse is made for parsing strings. not objects.

MbPCM
  • 457
  • 5
  • 12
-10

As simple as this !

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
CCC
  • 111
  • 5
  • 16