1

Goal: Use json_encode to format array data into a specified format

This is the needed format for the data after running through PHP json_encode:

NEEDED FORMAT

{
    "top_level_data": [
     {
        "extension": {},
        "sub_level_data1": 0
     }
    ]
}

When I use this PHP:

$data = array('top_level_data' => array('extension' => array(),
                                'sub_level_data1' => 0
                                )
            )
$data = json_encode($data);

I get this incorrect Output:

{
    "top_level_data":{
        "extension":[],
        "sub_level_data1": 0
        }
}

Question: How can I modify my php to include the {} and the [] in the correct places as the Needed Format?

2 Answers 2

1

It's not clear how you're generating $data; if it's by the assignment you show then you can just add an extra layer of array at top_level_data, and cast the extension value to an object:

$data = array('top_level_data' => array(
                                    array('extension' => (object)array(),
                                          'sub_level_data1' => 0
                                          )
                                        )
            );

If however you get the $data from another source, you can modify it like this:

$data['top_level_data']['extension'] = (object)$data['top_level_data']['extension'];
$data['top_level_data'] = array($data['top_level_data']);

Both methods yield this JSON:

{
    "top_level_data": [
        {
            "extension": {},
            "sub_level_data1": 0
        }
    ]
}

Demo on 3v4l.org

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

Comments

1

json_encode will encode sequence array with []. The sequence array should has index from 0 to n. For other array, associative array and object will encoded with {}. Use the JSON_FORCE_OBJECT parameter of json_encode all the array will be encoded with {}.

Example:

echo json_encode(range(1,3));                     // [1,2,3]
echo json_encode(array(2=>2));                    // {"2":2}
echo json_encode(range(1,3),JSON_FORCE_OBJECT);   // {"0":1,"1":2,"2":3}
echo json_encode((object)range(1,3));             // {"0":1,"1":2,"2":3}

Comments

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.