cbor-diag: Diagnostic notation for CBOR¶
See the project README file for installation, maintenance and license information.
This provides conversion functions between CBOR’s diagnostic notation (EDN) and its binary representation.
CBOR is a binary data format defined in RFC8949, often used IoT and modern security applications. Its diagnostic notation is a human readable form of it and looks similar to JSON (of which it is a superset thereof), and is defined in the edn-literals draft.
For producing binary representations of CBOR, and for processing them, the cbor2 package is recommended.
- cbor_diag.cbor2diag(encoded, *, pretty=True, from999=False)¶
Given a byte string containing encoded CBOR, produce some diagnostic notation.
>>> from cbor_diag import * >>> encoded = bytes.fromhex('a1016568656c6c6f') >>> cbor2diag(encoded) '{1: "hello"}'
By default, this recognizes several CBOR tags into application-oriented literals:
>>> encoded = bytes.fromhex("c105") >>> cbor2diag(encoded) "DT'1970-01-01T00:00:05+00:00'"
Key word arguments influence additional details:
With
pretty=False, no space is left after colons, commas etc., and no application-oriented literals are created:
>>> cbor2diag(encoded, pretty=False) '1(5)' >>> cbor2diag(cbor2.dumps([1, 2]), pretty=False) '[1,2]'
With
from999=True, CBOR tag 999 will be rendered as application oriented literal. Unlike other tags, this does not happen by default, as that tag is not intended to be used that way by default.
>>> cbor2diag(bytes.fromhex("d9 03e7 82 63 666f6f 63 626172"), from999=True) "foo'bar'"
- cbor_diag.diag2cbor(diagnostic, *, to999=False)¶
Given a string in CBOR diagnostic notation, produce its CBOR binary encoding.
>>> from cbor_diag import * >>> diag = '{1: "hello"}' >>> encoded = diag2cbor(diag) >>> encoded.hex() 'a1016568656c6c6f' >>> import cbor2 >>> cbor2.loads(encoded) {1: 'hello'}
Key word arguments influence additional details:
With
to999=True, unknown application-oriented literals are kept in tag 999 for the application to process further:
>>> cbor2.loads(diag2cbor("[1, spam'eggs']", to999=True)) [1, CBORTag(999, ['spam', 'eggs'])]