Parse JSON string into an array

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!