(==) Json problem

The == operator does not act as I expect with JSON values.
Is this documented anywhere? I didn’t find it here, anyway.

import Json.Encode as Json
json1 = Json.object [ ("oh", Json.string "no")]
json2 = Json.object [ ("oh", Json.string "no"), ("wow", Json.string "cool")]
--returns True
json1 == json2

Yes, JSON values break ==. There’s a note here in the docs for ==

Note: Equality (in the Elm sense) is not possible for certain types. For example, the functions (\n -> n + 1) and (\n -> 1 + n) are “the same” but detecting this in general is undecidable. In a future release, the compiler will detect when (==) is used with problematic types and provide a helpful error message. This will require quite serious infrastructure work that makes sense to batch with another big project, so the stopgap is to crash as quickly as possible. Problematic types include functions and JavaScript values like Json.Encode.Value which could contain functions if passed through a port.

1 Like

You can get around this by using Json.Encode.encode to convert the Values to a String. Or ideally, do the comparison before the data gets into a Value.

Example with Json.Encode.encode:

https://ellie-app.com/hhxhMWCJha1/0

3 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.