Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php json_decode removing attributes with null value

Tags:

json

php

I have a Json string and I am decoding it using php's json_decode.

The string

            "address": {
                "address": null,
                "postalCode": null,
                "phoneNumber": "",
                "city": null
            }

When I decode the string I get

            ["address"]=>
                  array(1) {
                  ["phoneNumber"]=>
                       string(0) ""

It essentially strips the attributes with null as a value i.e address, city. Can I prevent this from happening.

COMPLETE JSON

            {"cost": null,
            "receiptNumber": null,
            "receiptType": null,
            "labNo": 596726,
            "parentLabNo": 0,
            "investigation": "BS for mps",
            "patient": {
                "id": 168967,
                "fullName": "UVOGIN",
                "dateOfBirth": "1972-04-04 00:00:00",
                "gender": "Male"
            },
            "address": {
                "address": null,
                "postalCode": null,
                "phoneNumber": "",
                "city": null
            }
        }
like image 299
briankip Avatar asked Nov 01 '22 15:11

briankip


1 Answers

The attributes are not stripped, you might be stripping it yourself doing something like explained here: strip null values of json object

See example of your code:

$test = '{"address": {
            "address": null,
            "postalCode": null,
            "phoneNumber": "",
            "city": null
        }}';

$test_decoded = json_decode($test,true);
print_r($test_decoded);

//outputs as expected:
//Array ( [address] => Array ( [address] => [postalCode] => [phoneNumber] => [city] => ) )
like image 135
fellowworldcitizen Avatar answered Nov 15 '22 06:11

fellowworldcitizen