json_encode(): added option to turn only empty arrays into object #460
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR supersedes #454 in the sense that I've fixed up my repo :)
I ran into a situation whereby empty php arrays should be sent as objects but are serialized into JSON as an Array type, i.e.
[]
.The
JSON_FORCE_OBJECT
option will solve that, but that also affects numerically indexed arrays; in my case, I wanted a bit of both, so I'm proposingJSON_FORCE_EMPTY_OBJECT
that will serialize only empty arrays as objects, but filled arrays will be serialized according to their keys or other flags.A specific use-case is when the encoded value is passed to JavaScript; if an array is passed, you can add properties to it, but when you later do
JSON.stringify()
it returns an empty array. This is quite unlike PHP of course, because arrays can be both things, depending on whether it contains only numeric keys or not.I readily admit that this use-case is fairly uncommon :)