111

我需要将 JSON 对象字符串转换为 JavaScript 数组。

这是我的 JSON 对象:

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

我想拥有:

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

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

我怎样才能做到这一点?

4

11 回答 11

111
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/

于 2013-01-25T18:51:49.340 回答
71

如果你有一个格式良好的 JSON 字符串,你应该能够做到

var as = JSON.parse(jstring);

通过 AJAX 传输数组时,我一直这样做。

于 2013-10-30T17:23:36.273 回答
51

假设你有:

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

您可以通过以下方式获取值(几乎所有浏览器版本都支持):

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

或者简单地说:

Object.values(j)

输出:

["1", "2", "3", "4"]
于 2015-04-23T10:27:24.303 回答
28
function json2array(json){
    var result = [];
    var keys = Object.keys(json);
    keys.forEach(function(key){
        result.push(json[key]);
    });
    return result;
}

看到这个完整的解释:http ://book.mixu.net/node/ch5.html

于 2013-09-24T18:21:19.460 回答
19

这将解决问题:

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

或使用Object.entries()方法:

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

在这两种情况下,输出将是:

/* output: 
[['2013-01-21', 1], ['2013-01-22', 7]]
*/
于 2018-05-14T19:12:13.687 回答
5

您可以像这样将对象项插入数组

let obj = {
  '1st': {
    name: 'stackoverflow'
  },
  '2nd': {
    name: 'stackexchange'
  }
};
 
 let wholeArray = Object.keys(obj).map(key => obj[key]);
 
 console.log(wholeArray);

于 2019-02-17T10:32:59.573 回答
2

对@Mister Aqua 的 解决方案的一些修正

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

清凉丸:)

于 2021-12-03T10:31:21.127 回答
2

如果目标是创建一个对象数组,这里有一个解决方案,可以使用 Object.keys() 和 Object.values() 完成您尝试做的事情:

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, i) => data.push({[key]: Object.values(obj)[i]}))

或使用 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}))
于 2022-01-17T16:28:52.960 回答
1
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

console.log(obj.count);
// expected output: 42

console.log(obj.result);
// expected output: true
于 2021-09-14T15:36:14.597 回答
1

考虑有一个我们想要转换的 json 对象

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

您可以使用几种解决方案:

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

这些函数将任何对象转换为数组。一个返回一个包含所有键的数组,另一个返回所有值:

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

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

我不确定是否理解最初的问题,但解决方案可能是

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

2. Object.entries()

此功能是上述两者的混合:

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

它对最初的问题没有用,但是这个功能非常有用,我不得不提到它。特别是当value_是嵌套对象时。假设我们的值是这样的对象:

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

我们希望得到一个像这样的数组

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

我们需要Object.entries()用它们的值来获取我们所有的密钥。我们将从一个过于详细的代码开始:

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"}
//]

我们可以使用扩展运算符来简化我们的代码:

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"}
//]
于 2021-11-16T14:59:05.040 回答
-9

就这么简单!

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
于 2017-12-06T19:49:51.490 回答