tags:

views:

91

answers:

1

I am trying to create an JSON object out of a PHP array. The array looks like this:

$post_data = array('item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
    'is_public_for_contacts' => $public_contacts);

The code to encode the JSON look like this:

$post_data = json_encode($post_data);

The JSON file is supposed to look like this in the end:

{
    "item": {
        "is_public_for_contacts": false,
        "string_extra": "100000583627394",
        "string_value": "value",
        "string_key": "key",
        "is_public": true,
        "item_type_id": 4,
        "numeric_extra": 0
    }
} 

How can I encapsulate the created JSON code in the "item": { JSON CODE HERE }.

+7  A: 

Usually, you would do something like this:

$post_data = json_encode(array('item' => $post_data));

But, as it seems you want the output to be with "{}", you better make sure to force json_encode() to encode as object, by passing the JSON_FORCE_OBJECT constant.

$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);

"{}" brackets specify an object and "[]" are used for arrays according to JSON specification.

Cristian
i would add the `JSON_FORCE_OBJECT` in `json_encode($arr, JSON_FORCE_OBJECT)`
Dobiatowski
Is this correct?$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
Yes... but you can test it and tell us if it worked ;)
Cristian
maybe this will be helpful for someone - jsonwrapper http://www.boutell.com/scripts/jsonwrapper.html `json_(en|de)code` for earlier versions of PHP
robertbasic