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?
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?
Share Improve this question edited Jul 12, 2012 at 21:46 machineghost 35.7k32 gold badges173 silver badges260 bronze badges asked Jul 12, 2012 at 21:42 VikramVikram 3493 gold badges7 silver badges16 bronze badges 6-
var data = '{"...."}';data=JSON.parse(data);
, etc? – Rob W Commented Jul 12, 2012 at 21:44 - First, your object markup is invalid. Second, what have you tried? – Robert Commented Jul 12, 2012 at 21:45
- Wait... you changed your code and now there's no JSON – Dancrumb Commented Jul 12, 2012 at 21:45
- I'm not sure what you're hinting at here. I'm trying to take the day0 element out of JSON and put the numbers into an array. – Vikram Commented Jul 12, 2012 at 21:46
- Sorry, that was me; at first I thought it was a typo and I tried to correct it, but then I realized OP might actually have really screwy JSON code. – machineghost Commented Jul 12, 2012 at 21:46
3 Answers
Reset to default 7Something like this. Is that trailing ma intentional?
var getDayArray = JSON.parse(data).day0.split(",")
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 ma
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]}';
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.