HAVE you ever been stuck with an array of JSON strings when you really need an array of JSON objects? This is a common issue for anyone who works with JSON and any sort of key-value store such as Redis. Since it can’t store an entire JSON object, you have to parse it into a string. With one object you’re fine. If you have an object called “user” with the following data:

This could be stored by using JSON.stringify to turn it into a string like so:

Then when you take the data out of our key value store, we can reverse the process with JSON.parse:

But what happens when you have an array of several users represented as JSON strings? If you try to do JSON.parse, you’ll get an error after it parses the first user’s JSON object and encounters a comma instead of the end of the string. The error will look something like this:

SyntaxError: Unexpected token o

Use map

The solution is to use map. Map applies a function to every element of an array. In this case it iterates over each user inside the array “users” and parses it from a string into a JSON object. This yields an array of JSON elements instead of an array of strings. These JSON objects can then be passed off to your views or templating system.

That’s it. It’s just a one-liner. :)