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:
friends: [&quot;Jared&quot;, &quot;Keith&quot;, &quot;Sarah&quot;],
This could be stored by using JSON.stringify to turn it into a string like so:
userstr = JSON.stringify(user);
Then when you take the data out of our key value store, we can reverse the process with JSON.parse:
user = JSON.parse(userstr);
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:
throw e; // process.nextTick error, or ‘error’ event on first tick
SyntaxError: Unexpected token o
The solution is to use
. 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.
users = users.map(JSON.parse);
That’s it. It’s just a one-liner.