How to create a JSON object

How to create a JSON object

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Encapsulating PHP Arrays into Nested JSON Structures

You have a standard associative array in PHP containing fields like item_type_id, string_key, and boolean flags for public visibility. You've correctly identified that json_encode() is the tool to convert this data structure into a string representation. However, your target output requires a specific nesting: the entire dataset must be wrapped inside an object with the key "item".

The solution isn't about changing how json_encode functions; it's about how you construct the array before passing it to the encoder. In PHP, arrays are flexible structures that support arbitrary nesting. To achieve the desired JSON shape, you simply need to wrap your existing associative array within a new parent array before encoding.

Here is the direct implementation:

$post_data = [
    'item' => [
        '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
    ]
];

$json_string = json_encode($post_data);

By defining the structure with 'item' as the top-level key and placing your original variables inside it, json_encode automatically generates the nested object format you require. The resulting JSON string will look exactly like your target output, containing the "item" wrapper and all the inner properties.

Handling Missing Keys and Defaults

Your target JSON includes a field named numeric_extra with a value of 0, which does not appear in your source PHP array variables. If this field is optional but you want to ensure it always exists in the final output, you must initialize it explicitly in the array definition.

'post_data = [
    'item' => [
        // ... other fields
        'numeric_extra' => 0 
    ]
];

Failing to define this key results in a JSON object missing the property entirely. While some APIs are lenient, strict parsers will reject responses where expected keys are absent. Always verify your target schema against your source data definitions to catch these gaps early.

Formatting and Pretty Printing

The code snippet above generates a minified string: {"item":{"item_type_id":4,"string_key":"key",...}}. This is valid JSON, but it is difficult for humans to read or debug. If your application logs this output or displays it in a browser without an API wrapper, you might want the formatted version shown in your requirements.

You can achieve this by passing a second argument of JSON_PRETTY_PRINT (or JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE for specific formatting preferences) to json_encode. Note that this flag is only available in PHP 7.3+. If you are running an older version, you will need to pipe the output through a JSON formatter tool or use a library like monolog if logging requires structured data.

The Role of json_encode Options

When wrapping data for nested structures, consider whether your boolean values (true/false) need to be escaped as strings in specific legacy systems. By default, json_encode outputs PHP booleans as JSON booleans (true/false). If the receiving API expects "true" and "false" (strings), you would need a custom encoder or a manual string replacement, though this is rarely recommended as it breaks semantic meaning.

For most modern REST APIs, the default behavior of json_encode—where PHP arrays map directly to JSON objects and booleans remain booleans—is the correct approach. The nesting logic remains identical regardless of these options; the structure is defined solely by your array keys.

If you are working within a Laravel application, you might prefer using collect() or the Arr helper from the laravel/framework package to build these nested structures more dynamically, especially if the fields vary based on runtime logic. However, for static structures like this, direct array assignment remains the most performant and readable approach.

Our network