JsonPath-PHP icon indicating copy to clipboard operation
JsonPath-PHP copied to clipboard

JsonObject is turning empty objects into empty arrays

Open jaaufauvre opened this issue 5 years ago • 5 comments

Hi,

The JsonObject class turns empty objects into empty arrays and thus is unable to give back the original JSON representation.

For example:

{
 "item1": {},
 "item2": {}
}

Is returned as:

{
 "item1": [],
 "item2": []
}

Here is how to reproduce it:

 public function test() {
        $this->assertEquals('[{"item":"value"}]', (new JsonObject('[{"item":"value"}]'))->getJson());
        $this->assertEquals('{"item":"value"}', (new JsonObject('{"item":"value"}'))->getJson()); 
        $this->assertEquals('[]', (new JsonObject('[]'))->getJson());
        $this->assertEquals('{}', (new JsonObject('{}'))->getJson());  // FAILS!
    }
Failed asserting that two strings are equal.
Expected :'{}'
Actual   :'[]'

Best regards,

jaaufauvre avatar Apr 15 '19 14:04 jaaufauvre

Hi, nice catch!

I checked it. This happens because internally the library is turning everything into arrays.

I've started working in a fix for this. I'll update this issue when the PR is ready :)

I'm not sure how long this will take me (hopefully less than a couple weeks). It is not a simple fix and lately I have limited time for this but I'll do my best!

If you happen to have a fix ready for this before I say anything feel free to open a PR ;)

Galbar avatar Apr 17 '19 20:04 Galbar

Actually, I went ahead and opened the WIP PR :)

Galbar avatar Apr 17 '19 20:04 Galbar

Unfortunately I don't have a fix.

An idea could be to use objects instead of associative arrays for the internal representation.

This can be achieved with json_decode($json) instead json_decode($json, true).

jaaufauvre avatar Apr 18 '19 09:04 jaaufauvre

FYI, I am working on this and have something that kind of works in my laptop (I haven't forgotten :wink: ) I've just been busy...

Galbar avatar Jun 05 '19 18:06 Galbar

Update: There is a WIP PR with half an implementation of this: https://github.com/Galbar/JsonPath-PHP/pull/25

Fixing this requires a bigger change than I'm willing to do. Sorry, but it is not happening, unless someone really wants it and implements it :/

Galbar avatar May 06 '20 16:05 Galbar