Skip to content

Conversation

@thekid
Copy link
Member

@thekid thekid commented May 3, 2025

This pull request changes JSON objects to be returned as an instance of text.json.JsonObject instead of as an associative array.

In a nutshell

use text\json\Json;

$empty= Json::read('{}');                // JsonObject([])
$value= Json::read('{"key" : "value"}'); // JsonObject(['key' => 'value'])

This makes us able to distinguish {} from [], which previously would have both yielded an empty array:

use text\json\Json;

$roundtrip= Json::of(Json::read('{}'));  // Before: '[]' (❌), After: '{}' (✅)

Decision to create dedicated class

We could have used StdClass like json_decode() does but would break BC as array access does not work, yielding Cannot use object of type stdClass as array.

use text\json\Json;

$value= Json::read('{"color" : "green"}');

// All of the following would have been broken, throwing exceptions 💣
isset($value['color']);
unset($value['color']);
$color= $value['color'];
$n= sizeof($value);

There is, however, still some BC breaks. If you pass the returned value to a function with an array type hint, use the + operator for a union, use is_array(), any of the array functions or rely on an assignment creating a copy, or if you use empty(), the behavior will be different!

@thekid
Copy link
Member Author

thekid commented May 3, 2025

This makes us able to distinguish {} from [], which previously would have both yielded an empty array:

See #16

@thekid
Copy link
Member Author

thekid commented May 3, 2025

Closed in favor of #16

@thekid thekid closed this May 3, 2025
@thekid thekid deleted the refactor/json-object branch May 3, 2025 12:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants