1

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).

10

1 Answer 1

2

See this answer: https://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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Yeah, that's strange. Maybe that depends on your PHP version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.