Reputation: 1671
I'm writing data and string parsers for a JSON variant. My understanding is that standard JSON is incompatible with PHP, since PHP uses the same datatype (Array) for JSON arrays and JSON objects. This problem is severe with empty JSON arrays and objects, since once converted to a PHP value, they are indistinguishable. So if you start with JSON strings "[]" and "{}", converting them to values and then back to JSON makes them look the same.
My basic idea is to require PHP arrays intended to be represented as JSON objects, especially empty arrays that should be encoded or stringified to "{}", to be represented differently in PHP programs, so proper error checking and JSON conversion can be done. Of course, for nonempty PHP arrays, it is possible to determine programmatically whether they have indices that are successive integers starting at 0 or not. But such a check fails to be useful if empty JSON arrays and objects are also to be properly distinguished.
The actual distinction discussed here is important to choose well, as programmers will be required to generate and type-check PHP Arrays differently depending on whether they are intended to correspond to "[]" or "{}" syntax in JSON.
So, my question is: what distinctive representation is best? The main candidates are:
for PHP associative arrays representing JSON objects:
$JSONobject=(object){};
$JSONobject=new stdClass();
$JSONobject=json_decode("{}");
I list these separately as I am not sure if they all have the same internal representation.
For PHP sequential list arrays representing JSON arrays, the Array datatype would be used unchanged, so an empty JSON array would be generated by $JSONarray=[];
or $JSONarray=new Array();
Upvotes: 1
Views: 89
Reputation: 1671
I have an answer to my own question, as a result of experimentation: I've found that json_decode("[]")
results in a zero-length array, and json_decode("{}")
results in a standard class object with no properties, no inheritance, and no methods. Furthermore, json_encode(json_decode ("[]")
results in "[]"
, which is correct, and json_encode(json_decode ("{}")
results in "{}"
, which is also correct.
So PHP itself chose my proposed answer to disambiguate the PHP Array type into two separate subtypes (Array and Class Object).
I think this answers my question in the affirmative. Furthermore, the three ways I listed above for representing JSON "{}" are indeed equivalent, as I guessed.
I hope this question and answer help those who may be puzzled by this issue in the future. The ambiguity of using Array to represent both lists and associative maps is permitted (and probably recommended) to be resolved in just the way I described.
Upvotes: 1