Parse JSON string into an array

前端 未结 3 1683
别那么骄傲
别那么骄傲 2021-01-03 04:52

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         


        
相关标签:
3条回答
  • 2021-01-03 05:20

    Something like this. Is that trailing comma intentional?

    var getDayArray = JSON.parse(data).day0.split(",")
    
    0 讨论(0)
  • 2021-01-03 05:25

    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]}';
    
    0 讨论(0)
  • 2021-01-03 05:37

    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.

    0 讨论(0)
提交回复
热议问题