JSON
This section provides an overview of the cbor_serialization json tools.
JSON to CBOR
JSON can be converted to CBOR with the toCbor(JsonString): seq[byte] API.
The implementation converts JSON as described in RFC8949.
Requires the json_serialization nimble package.
Import json_utils:
import cbor_serialization, cbor_serialization/json_utils
Encode a JSON string to CBOR bytes:
let jsonDecoded = """{"cborrpc":"2.0","method":"subtract","params":[42,3],"id":1}"""
let encoded = toCbor(jsonDecoded.JsonString)
CBOR to JSON
CBOR can be converted to JSON with the toJson(CborBytes): string API.
The implementation converts CBOR as described in RFC8949.
Note some CBOR types do not have direct analogs in JSON:
- NaN, -Infinity, Infinity, undefined, and simple values are converted to null.
seq[byte]is base64 encoded.- Tags 2, 21 and 22 are base64 encoded.
- Tag 3 is base64 encoded and prefixed with
~. - Tag 23 is hex encoded.
- All tag numbers are lost (not encoded); only their value is encoded.
- Non-string map keys are stringified using
toJsonwhich can create key collisions.
Requires the json_serialization nimble package.
Import json_utils:
import cbor_serialization, cbor_serialization/json_utils
Encode CBOR bytes to a JSON string:
doAssert toJson(encoded.CborBytes) == jsonDecoded