Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

When I do json_encode from this array:

array('aps' => array(
                     'alert' => array(
                                     'param1'=>array('string'), 
                                     'param2'=>'string' )));

I'm getting this JSON object:

{
    "aps" :    {
      "alert" :         {
            "param1" :             {
                "0" : "string"
            },
            "param2" : "string"
        }
    }
}

Instead of

{
    "aps" :    {
      "alert" :         {
            "param1" :             
                ["string"],

            "param2" : "string"
        }
    }
}

It seems to work right when the param1 array is not a single item. How could I fix it? The Json is created from a third party bundle, so I should format the array in PHP so that I could get the correct JSON on json_encode (param1 as a list).

share|improve this question
    
@ShankarDamodaran: What's wrong with it apart from the missing quotes, which are really beside the point? – Jon May 7 '14 at 10:32
2  
I cannot reproduce. I suspect you rewrote your code and output for the question—you should post some real code we can test. – Álvaro González May 7 '14 at 10:34
1  
@ManoloSalsas: Your expected output is what you should be getting, and indeed what I am getting. – Jon May 7 '14 at 10:35
1  
Sorry but what you claim to be your actual JSON does not even pass the JSONLint validator. I'm sure you honestly think you've posted the relevant code but facts suggest is isn't the case. – Álvaro González May 7 '14 at 11:10
1  
No, it isn't. The problem is that you are typing manually some code that you wrongly think that illustrates the issue. You should be using the clipboard to post real code that you've tested yourself. – Álvaro González May 7 '14 at 11:16

See this answer: http://stackoverflow.com/a/11722121/1466341

And more info here: http://www.php.net/manual/en/function.json-encode.php

Note: 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.

In your case everything should work fine, but I guess you have simplified your PHP array in this example. So, idea is simple - if your PHP array don't have all keys sequential, then json_encode will treat them as keys of object.

share|improve this answer
    
I knew that. But I supposed that if there is only one key, it is treating it as an associative one. But I think that I was wrong with it. – Manolo May 7 '14 at 11:46
    
Yeah, that's strange. Maybe that depends on your PHP version. – DarkSide May 7 '14 at 22:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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