jwadhams / json-logic

Build complex rules and serialize them to JSON
MIT License
116 stars 13 forks source link

truthiness of objects #34

Open gregsdennis opened 2 years ago

gregsdennis commented 2 years ago

The table presented on the website doesn't list how to treat objects (empty or non-empty) in regard to truthiness. Is this defined somewhere else?

On your playground,

{
  "if": [
    {}, 
    true, 
    false
  ]
}

returns true, while

{
  "if": [
    { "test": "value" },
    true,
    false
  ]
}

returns nothing.

jwadhams commented 2 years ago

So part of the problem is that JsonLogic is pretty crummy at handling inline objects, because it tries to use {"test":"value"} as logic too. Way at the bottom of the page there should be an error message

Unrecognized operation test

But even if we push it into a variable, I bet empty objects are sort of inconsistent by implementation.

Do you have an opinion what it should be? I think in both languages I maintain implementations for (JavaScript and PHP) objects are truthy, even empty objects. That seems the easiest to make consistent (you wouldn't have to wonder about whether an object with zero public attributes but some private attributes should behave, do methods count as properties in your language, etc etc)

gregsdennis commented 2 years ago

I have a client who's expecting existence to be truthy. (See linked issue.) The specific use case has a non-empty object, so I'm not sure about empty objects.

Personally I have no preference, other than it should be defined. I just want to know what to implement.

Non-empty objects being truthy and empty objects being falsy would align with how arrays are treated.

gregsdennis commented 2 years ago

@jwadhams do you have any more information on this?