Skip to content
Advertisement

How to add square braces around subarray data inside of a json encoded string?

When trying to access an API the JSON array must be parsed like this

JavaScript

But when i’m doing the following code

JavaScript

it returns the json array without squared brackets as follows

JavaScript

I’ve spent hours trying to figure out how to fix this and just can’t think of a solution

Advertisement

Answer

You need to wrap things in another array:

JavaScript

This will be more understandable if we use the equivalent PHP 5.4 array syntax:

JavaScript

Compare this with the JSON:

JavaScript

The only thing to explain is why one of the PHP arrays remains an array [] in JSON while the other two get converted to an object {}. But the documentation already does so:

When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement