Javascript 将 JSON 字符串解析为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11461142/
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
Parse JSON string into an array
提问by Vikram
I'm trying to parse a string from JSON and turn those elements into an array in Javascript. Here's the code.
我正在尝试从 JSON 解析字符串并将这些元素转换为 Javascript 中的数组。这是代码。
var data = "{"fname":"Todd","lname":"James","cascade":"tjames","loc":"res","place":"home", "day0":"0,1,2,3,"}";
var getDay = data.day0;
var getDayArray = getDay.split(",");
Essentially, I'm trying to get day0, which is 0,1,2,3, and turn it into an array with a structure of
本质上,我正在尝试获取 day0,即 0,1,2,3,并将其转换为具有以下结构的数组
[0] = 0
[1] = 1
[2] = 2
[3] = 3
What is the best way to go about doing this?
这样做的最佳方法是什么?
回答by Mike Robinson
Something like this. Is that trailing comma intentional?
像这样的东西。尾随逗号是故意的吗?
var getDayArray = JSON.parse(data).day0.split(",")
回答by Brandon Buck
This is built into most modern browser JavaScript engines. Depending on what environment you are targeting you can simply do:
这是内置在大多数现代浏览器 JavaScript 引擎中的。根据您的目标环境,您可以简单地执行以下操作:
var data = JSON.parse(jsonString);
day0 = data.day0.split(",");
It's pretty simple. If you are targeting environments that don't have access to a built in JSON object you should try this JSON project.
这很简单。如果您的目标环境无法访问内置 JSON 对象,您应该尝试这个 JSON 项目。
回答by Dancrumb
Most modern browsers have support for JSON.parse()
. You would use it thusly:
大多数现代浏览器都支持JSON.parse()
. 你会这样使用它:
var dataJSON = '{"fname":"Todd","lname":"James","cascade":"tjames","loc":"res","place":"home", "day0":"0,1,2,3"}'; // You need to remove the trailing comma
var data = JSON.parse(dataJSON);
var getDay = data.day0;
var getDayArray = getDay.split(",");
However, it might be better to modify whatever is generating the value for dataJSON, to return
但是,最好修改生成 dataJSON 值的任何内容,以返回
var dataJSON = '{"fname":"Todd","lname":"James","cascade":"tjames","loc":"res","place":"home", "day0":[0,1,2,3]}';