可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm trying to parse a string from JSON and turn those elements into an array in Javascript. Here's the code.
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
[0] = 0 [1] = 1 [2] = 2 [3] = 3
What is the best way to go about doing this?
回答1:
Something like this. Is that trailing comma intentional?
var getDayArray = JSON.parse(data).day0.split(",")
回答2:
Most modern browsers have support for JSON.parse()
. You would use it thusly:
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
var dataJSON = '{"fname":"Todd","lname":"James","cascade":"tjames","loc":"res","place":"home", "day0":[0,1,2,3]}';
回答3:
This is built into most modern browser JavaScript engines. Depending on what environment you are targeting you can simply do:
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.