Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Docs request] lenient decoding explained #262

Open
avanov opened this issue May 29, 2021 · 2 comments
Open

[Docs request] lenient decoding explained #262

avanov opened this issue May 29, 2021 · 2 comments

Comments

@avanov
Copy link

avanov commented May 29, 2021

Hi!

The current docs section for https://hackage.haskell.org/package/cborg-json-0.2.2.0/docs/Codec-CBOR-JSON.html#v:decodeValue omits mentioning of the effect lenient argument has on data decoding. I'd appreciate it if the docs mentioned it in a quick example of how the argument affects decoding of the same input structure. Thanks!

@thoughtpolice
Copy link
Collaborator

Yes, this is worth pointing out. For people who end up looking here, the essential impact is this: CBOR has a notion of types for the keys in a Map, while JSON has no such equivalent for an object, a key is always a string. This makes CBOR maps a strict superset of JSON objects, so you cannot always convert from one to the other.

More specifically: when you decode a CBOR Map into JSON, the question then becomes, what should the JSON equivalent for following two-entry CBOR map be?

True:Bool -> 1
"True":String -> 2

That is, the first entry is a value of type CBOR Bool, while the second is of type String. This CBOR can't trivially be converted to JSON; the only apparent trivial mapping would be:

{
  "True": 1,
  "True": 2
}

Which is clearly an invalid JSON object due to collision of the key names.

So the rules are this:

  • By default, with lenient = False, the only kind of Map that can be decoded is one that only has Strings as the key values. If any non-String key value is found, emitting JSON fails.
  • If lenient = True, then if a Map is encountered with a non-String key, that key is show'd and converted to a String, and then returned. This means the above CBOR (valid) map would be accepted, but the resulting JSON would still be invalid as above: duplicate keys can now occur.

@avanov
Copy link
Author

avanov commented Aug 12, 2021

It's a great write-up, thank you! If it doesn't take too much effort on your side, I wouldn't hesitate to put it into the docstring, as it really explains the intent of the bool flag in the function signature.

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

No branches or pull requests

2 participants