Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I am having a problem using json_encode to generate a json encoded string from an array.

The section of the array in question looks like this

RatingDistribution (Array, 11 elements)
    0 (Array, 1 element)
        0 (String, 3 characters ) 4.5
    1 (Array, 1 element)
        1 (String, 4 characters ) 11.9
    2 (Array, 1 element)

But produces this in the string:

"RatingDistribution":[["4.5"],{"1":"11.9"},

I would expect this:

"RatingDistribution":[{"0":"4.5"},{"1":"11.9"},

All I'm doing is this:

$result = json_encode($array);

Have I done something wrong or do I need more code to ensure the 0 key is present?

Cheers Andy

share|improve this question
1  
can you post the php code where you get the array? or print_r the array? Looks like your forearch is wrong. – Federico Giust Mar 8 at 9:37
I think it screws up on the second element (index 1) becuase it's sub array starts as 1 and thus gets interpreted as a string key. – TFennis Mar 8 at 9:39

marked as duplicate by hakre, dragon112, Ocramius, Jon, Jocelyn Mar 8 at 16:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

The result you are getting should be expected; json_encode detects that you are only using numeric keys in the array, so it translates that to an array instead of an object in JSON. Most of the time, that's exactly what you want to do.

If for some reason you don't (why?), in PHP >= 5.3 you can use the JSON_FORCE_OBJECT flag to get your desired output:

$result = json_encode($array, JSON_FORCE_OBJECT);
share|improve this answer
the behaviour is a little odd, for example the first value will decode to an array where all subsequent values will be objects. – user2147830 Mar 8 at 10:29
I suspect we will have to use JSON_FORCE_OBJECT – user2147830 Mar 8 at 10:30
@user2147830: Not really odd IMHO. The second array's first key is not 0, which is enough for the heuristic to decide "OK, this is an associative array". – Jon Mar 8 at 10:39

Cou can try to cast the array key to a string for example with strval or (string).

share|improve this answer
1  
This should be comment! – sandip Mar 8 at 9:39
That was my first thought but it made no difference, enclosing it in quotes does but it makes very messy json :) – user2147830 Mar 8 at 10:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.