Sunday, 15 September 2013

Encoding JSON as an object, even when it has a zero-index

Encoding JSON as an object, even when it has a zero-index

I have an array that might look something like this:
array(
1 => "foo",
4 => "bar"
)
When I json_encode it, it turns out something like this:
{
"1": "foo",
"4": "bar"
}
That's exactly how I need it.
However, there is the possibility that the array would look like this:
array(
0 => "baz"
)
In which case I would want the JSON to end up like this:
{
"0": "baz"
}
But instead, it ends up like this:
[
"baz"
]
Is there any way I can force the JSON encoder to assume that this is an
object instead of an array?
EDIT: Sorry, I simplified it for this post, but I realise now it's quite
important: This array is nested in another array, which must be an array,
not an object.
EDIT 2: Example of this:
array(
0 => array(
0: "baz"
),
1 => array(
4: "bar"
)
)
needs to become:
[
{
0: "baz"
},
{
4: "bar"
}
]

No comments:

Post a Comment