square / pjson

JSON <=> PHP8+ objects serialization / deserialization library
Apache License 2.0
109 stars 7 forks source link

[Feature] Allow dot-notation for JSON paths #9

Open szainmehdi opened 1 year ago

szainmehdi commented 1 year ago

Using the example definition in the README, it would be great (and familiar to Laravel users) to define nested JSON mappings using dot-notation.

class Schedule
{
    use JsonSerialize;

    #[Json('data.start')]
    protected int $start;

    #[Json('data.end')]
    protected int $end;

    public function __construct(int $start, int $end)
    {
        $this->start = $start;
        $this->end = $end;
    }
}
khepin commented 1 year ago

My problem with dot notation is that this:

{
    "data": {
        "name": "bob"
    },
    "data.name": "alice"
}

is valid json

khepin commented 1 year ago

It's also inconsistently implemented even within laravel itself. Arr::get vs. data_get.

szainmehdi commented 1 year ago

Oh that's a good point about data.name being a valid JSON key.

Generally speaking I like the simplicity of dot-notation, and it saves a few keystrokes. But I understand why it may not make sense for this library 👍

khepin commented 1 year ago

Actually the real issue when using dot notation wouldn't be deserializing but serializing. IE: where do I put a value that has a path of data.name? When de-serializing you could try both, when serializing you're .... kinda stuck.