从 JSON 创建数组 - Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8086475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create array from JSON - Javascript
提问by gberg927
I have a JSON file that I would like to create an array from.
我有一个 JSON 文件,我想从中创建一个数组。
Here is the JSON data.
这是 JSON 数据。
{
"table": {
"columnNames": ["column1", "column2", "column3", "column4"],
"columnTypes": ["String", "String", "String", "String"],
"rows": [
["data00", "data01", "data02", "data03"],
["data10", "data11", "data12", "data13"],
["data20", "data21", "data22", "data23"],
["data30", "data31", "data32", "data33"]
]
}
}
I need to create an array from the objects in the "rows" section.
我需要从“行”部分中的对象创建一个数组。
Any help would be appreciated!
任何帮助,将不胜感激!
Thanks!!!
谢谢!!!
EDIT
编辑
Would it be possible to create a hash table out of the data in rows? Also, how would you perform JSON.parse on a json file? Thanks
是否可以从行中的数据中创建一个哈希表?另外,您将如何对 json 文件执行 JSON.parse?谢谢
回答by lonesomeday
Do you mean you want to get a single array holding all the values?
你的意思是你想得到一个包含所有值的数组?
var rows = [];
for (var i = 0; i < data.table.rows.length; i++) {
rows.push.apply(rows, data.table.rows[i]);
}
See MDN docs for push
and apply
.
This assumes that you've stored the data from your question in a variable data
. If you only have it as a JSON string, you'll need to convert it with JSON.parse
.
这假设您已将问题中的数据存储在变量中data
。如果您只将其作为 JSON 字符串,则需要将其转换为JSON.parse
.
回答by Marc B
JSON is basically javascript already, so once you've decoded the JSON stringback to a native JS data structure, then it'd be a simple matter of doing:
JSON 基本上已经是 javascript 了,所以一旦你将 JSON 字符串解码回原生 JS 数据结构,那么就很简单了:
var rowsarray = decoded_json.table.rows;