Kevin Weber
Kevin Weber

Reputation: 198

PHP to JSON encoding

I am trying to write this using php and json_encode

{"patient": {"demographics": {}}

}

This is the Array I am using with json encode.

Array("patient" =>  Array("demographics" =>  Array()))

When I echo the output, this is what I get:

{"patient":{"demographics":[]}}

I really think this is a stupid mistake ob my part. All help is appreciated.

Upvotes: 1

Views: 106

Answers (2)

SirDarius
SirDarius

Reputation: 42869

You can also try this:

json_encode(Array("patient" =>  Array("demographics" => new stdClass)));

This way you can have empty arrays and empty objects in the same JSON, which would not be possible using the other answer.

Upvotes: 0

Marc B
Marc B

Reputation: 360562

try

json_encode($your_array, JSON_FORCE_OBJECT)

as per the docs: http://php.net/json_encode

By default, php arrays stay arrays ([]) when json'd, unless there's a single non-numeric key, in which case it'll be an object

Upvotes: 9

Related Questions