Cast a String Array of JSON Objects to JSON in Javascript

Cast a String Array of JSON Objects to JSON in Javascript

I recently came across a situation where I had to to save an array of objects to a local device so that I could pull that info up later. My problem was that I had to change that array of objects into a string before saving it. Thus, I had to cast a string array of JSON Objects to JSON in Javascript. For those of you just looking for the solution here it is. For those that want to recreate the problem, read on.

The Solution

//Create the string array
data = '[{"data_one":"a", "data_two":"b"}]'
// Just use JSON.parse() and you're done!
json_data = JSON.parse(data)
// Now you can access elements per usual
json_data[0] 

My Setup

Recreating the Parsing Problem

The issue was identified when I tried to access the first element of my array and I got ‘[‘ back.

//Create the string array
data = '[{"data_one":"a", "data_two":"b"}]'
// Trying to access the first element will give you only the bracket
data[0]
// this should output '[' because node thinks you have a string
// Just use JSON.parse() and you're done!
json_data = JSON.parse(data)
// Now you can access elements per usual
json_data[0] 
// or a key
json_data[0]["data_one"]

That’s it. If you saved a string, use this to get your data back into an array and you should be set and now know how to cast a string array of JSON objects to JSON in Javascript. Check out a similar issue I had here in Python! Happy coding!

Leave a Comment