nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.5k stars 6.68k forks source link

CBOR byte string support #1129

Closed daviddesberg closed 5 years ago

daviddesberg commented 6 years ago

Currently, the CBOR feature of the library only supports writing strings out as UTF-8 and doesn't support byte arrays as described in the CBOR standard. I'd like to implement COSE on top of this library, but in order to do that, byte string support is needed.

I'm happy to submit a pull request for this, but I wanted to check in advance if this is something you'd be open to

sijohans commented 5 years ago

This would be a nice an useful feature. This library can be used for creating tests towards a c target that parses CBOR and the library allows for writing easy to understand code when creating the data that the target should handle.

For test the following changes have been made:

The problem with this is the cases when sending an actual string that starts with "0x" and has a valid hex representation following. For the above mentioned use case I am fine with this corner case, but I understand that this might not be acceptable for the library in general.

Interesting is how the CBOR playground (http://cbor.me/) handles/presents this:

CBOR Representation
A1               # map(1)
   65            # text(5)
      6279746573 # "bytes"
   45            # bytes(5)
      0011223344 # "\x00\x11\"3D"

JSON Representation
{"bytes": h'0011223344'}

Can this issue be reopened?

ecorm commented 4 years ago

Check out the WAMP protocol for ideas on JSON-encoding a binary blob: https://wamp-proto.org/_static/gen/wamp_latest.html#binary-conversion-of-json-strings

The basic idea is to prepend a Base64-encoded string with a nul character.

OmnipotentEntity commented 4 years ago

For those still following this issue, #1662 addresses this issue, and is finally in a complete state, and is ready for review and merge.

nlohmann commented 4 years ago

The functionality was added by merging #1662.