logo

CBOR.js - JavaScript API

Abstract

This document describes a JavaScript API for encoding and decoding data in the CBOR [RFC8949link] format. Through platform independent definitions of deterministic encoding and a textual representation of CBOR data items, compatible implementations could, together with the rich set of data types, provide a viable alternative to JSON.

Table of Contents

n/a1.  Introduction
n/a2.  CBOR Wrapper Objects
n/a2.1.  CBOR.Int
n/a2.1.1.  CBOR.Int Methods
n/a2.1.1.1.  getInt()
n/a2.1.1.2.  getInt8()
n/a2.1.1.3.  getUint8()
n/a2.1.1.4.  getInt16()
n/a2.1.1.5.  getUint16()
n/a2.1.1.6.  getInt32()
n/a2.1.1.7.  getUint32()
n/a2.1.1.8.  getInt64()
n/a2.1.1.9.  getUint64()
n/a2.1.1.10.  getBigInt()
n/a2.2.  CBOR.BigInt
n/a2.2.1.  CBOR.BigInt Methods
n/a2.2.1.1.  getInt64()
n/a2.2.1.2.  getUint64()
n/a2.2.1.3.  getBigInt()
n/a2.3.  CBOR.Float
n/a2.3.1.  CBOR.Float Methods
n/a2.3.1.1.  getFloat16()
n/a2.3.1.2.  getFloat32()
n/a2.3.1.3.  getFloat64()
n/a2.3.2.  CBOR.Float Properties
n/a2.3.2.1.  length
n/a2.4.  CBOR.String
n/a2.4.1.  CBOR.String Methods
n/a2.4.1.1.  getString()
n/a2.5.  CBOR.Bytes
n/a2.5.1.  CBOR.Bytes Methods
n/a2.5.1.1.  getBytes()
n/a2.6.  CBOR.Boolean
n/a2.6.1.  CBOR.Boolean Methods
n/a2.6.1.1.  getBoolean()
n/a2.7.  CBOR.Null
n/a2.8.  CBOR.Array
n/a2.8.1.  CBOR.Array Methods
n/a2.8.1.1.  add()
n/a2.8.1.2.  get()
n/a2.8.1.3.  toArray()
n/a2.8.2.  CBOR.Array Properties
n/a2.8.2.1.  length
n/a2.9.  CBOR.Map
n/a2.9.1.  CBOR.Map Methods
n/a2.9.1.1.  set()
n/a2.9.1.2.  get()
n/a2.9.1.3.  getConditional()
n/a2.9.1.4.  containsKey()
n/a2.9.1.5.  remove()
n/a2.9.1.6.  getKeys()
n/a2.9.1.7.  setSortingMode()
n/a2.9.2.  CBOR.Map Properties
n/a2.9.2.1.  length
n/a2.10.  CBOR.Tag
n/a2.10.1.  CBOR.Tag Methods
n/a2.10.1.1.  getTagNumber()
n/a2.10.1.2.  getTaggedObject()
n/a3.  Common Wrapper Methods
n/a3.1.  encode()
n/a3.2.  clone()
n/a3.3.  equals()
n/a3.4.  toDiag()
n/a3.5.  toString()
n/a3.6.  isNull()
n/a3.7.  checkForUnread()
n/a3.8.  scan()
n/a4.  Decoding CBOR
n/a4.1.  CBOR.decode()
n/a4.2.  CBOR.initDecoder()
n/a4.3.  Decoder.setDeterministicMode()
n/a4.4.  Decoder.setSequenceMode()
n/a4.5.  Decoder.setNaNSupport()
n/a4.6.  Decoder.decodeWithOptions()
n/a4.7.  Decoder.getByteCount()
n/a4.8.  CBOR.diagDecode()
n/a4.9.  CBOR.diagDecodeSequence()
n/a5.  Utility Methods
n/a5.1.  CBOR.addArrays()
n/a5.2.  CBOR.compareArrays()
n/a5.3.  CBOR.toHex()
n/a5.4.  CBOR.fromHex()
n/a5.5.  CBOR.toBase64Url()
n/a5.6.  CBOR.fromBase64Url()
n/a6.  JavaScript Number Considerations
n/a6.1.  Integer Numbers
n/a6.2.  Floating Point Numbers
n/a7.  Diagnostic Notation
n/a8.  Deterministic Encoding
n/a9.  Using the CBOR API
n/a9.1.  Encode CBOR
n/a9.2.  Decode CBOR
n/a9.3.  Using Diagnostic Notation
n/a10.  Version

1.  Introduction

This document describes a JavaScript API for encoding and decoding data in the CBOR [RFC8949link] format. The API loosely mimics the "JSON" object by exposing a single global object, unsurprisingly named "CBOR". To minimize the need for application developers having detailed knowledge of CBOR, the CBOR.js API provides a set of high level wrapper objects. The wrapper objects are used for encoding CBOR data items, as well as being the result of CBOR decoding. The CBOR.js API provides some specific features including: Note: in this specification CBOR data items are subsequently referred to as CBOR objects.
Although this document describes a JavaScript API, it could also serve as a guide for CBOR implementations for other software platforms, with the goal of creating the foundation for cross platform interoperability. Due to this consideration, the level of CBOR support provided by the API is of the type "general purpose", avoiding constructs that are specific to JavaScript, like undefined and typed arrays beyond Uint8Array.

2.  CBOR Wrapper Objects

This section describes the wrapper objects and their specific methods. Note that using the "new" operator with a wrapper object is flagged as an error. The following table lists the wrapper objects and their relation to the CBOR objects supported by this specification:
CBOR ObjectWrapper ObjectJavaScript
integer CBOR.Int Number [1]
bignum CBOR.BigInt BigInt [1]
floating point CBOR.Float Number [2]
byte string CBOR.Bytes Uint8Array
text string CBOR.String String
true/false CBOR.Boolean Boolean
null CBOR.Null
array CBOR.Array
map CBOR.Map
tag CBOR.Tag
  1. See also Integer Numbers.
  2. See also Floating Point Numbers.

Note that this implementation does not support CBOR "simple" values beyond true, false, null, and the three floating point variants.

The wrapper concept adds strict type checking to the API. That is, if an application expects a CBOR integer and calls getInt32(), an exception will be thrown if the referenced object is not an instance of CBOR.Int or if the CBOR integer does not fit in a 32-bit two-complement representation.

See also Common Wrapper Methods.
2.1.  CBOR.Int
SyntaxCBOR.Int(value)
DescriptionConstructor. Creates a CBOR integer wrapper object. See also Integer Numbers.
ParameterTypeDescription
valueNumberInteger to be wrapped.
ReturnsDescription
CBOR.IntWrapper object.
2.1.1.  CBOR.Int Methods
2.1.1.1.  getInt()
SyntaxgetInt()
DescriptionGet CBOR integer.
Values outside of -253+1 to 253-1 will cause an exception to be thrown. See also getBigInt().
ReturnsDescription
NumberDecoded integer.
2.1.1.2.  getInt8()
SyntaxgetInt8()
DescriptionGet CBOR integer.
Values outside of -0x80 to 0x7f will cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.3.  getUint8()
SyntaxgetUint8()
DescriptionGet CBOR integer.
Values outside of 0 to 0xff will cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.4.  getInt16()
SyntaxgetInt16()
DescriptionGet CBOR integer.
Values outside of -0x8000 to 0x7fff will cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.5.  getUint16()
SyntaxgetUint16()
DescriptionGet CBOR integer.
Values outside of 0 to 0xffff will cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.6.  getInt32()
SyntaxgetInt32()
DescriptionGet CBOR integer.
Values outside of -0x80000000 to 0x7fffffff will cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.7.  getUint32()
SyntaxgetUint32()
DescriptionGet CBOR integer.
Values outside of 0 to 0xffffffff will cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.8.  getInt64()
SyntaxgetInt64()
DescriptionGet CBOR integer.
Values outside of -0x8000000000000000 to 0x7fffffffffffffff will cause an exception to be thrown.
ReturnsDescription
BigIntDecoded big integer.
2.1.1.9.  getUint64()
SyntaxgetUint64()
DescriptionGet CBOR integer.
Values outside of 0 to 0xffffffffffffffff will cause an exception to be thrown.
ReturnsDescription
BigIntDecoded big integer.
2.1.1.10.  getBigInt()
SyntaxgetBigInt()
DescriptionGet CBOR integer of any size. See also Integer Numbers.
ReturnsDescription
BigIntDecoded big integer.
2.2.  CBOR.BigInt
SyntaxCBOR.BigInt(value)
DescriptionConstructor. Creates a CBOR big integer wrapper object. See also Integer Numbers.
ParameterTypeDescription
valueBigIntBig integer to be wrapped.
ReturnsDescription
CBOR.BigIntWrapper object.
2.2.1.  CBOR.BigInt Methods
2.2.1.1.  getInt64()
SyntaxgetInt64()
DescriptionGet CBOR integer.
Values outside of -0x8000000000000000 to 0x7fffffffffffffff will cause an exception to be thrown.
ReturnsDescription
BigIntDecoded big integer.
2.2.1.2.  getUint64()
SyntaxgetUint64()
DescriptionGet CBOR integer.
Values outside of 0 to 0xffffffffffffffff will cause an exception to be thrown.
ReturnsDescription
BigIntDecoded big integer.
2.2.1.3.  getBigInt()
SyntaxgetBigInt()
DescriptionGet CBOR integer of any size. See also Integer Numbers.
ReturnsDescription
BigIntDecoded big integer.
2.3.  CBOR.Float
SyntaxCBOR.Float(value)
DescriptionConstructor. Creates a CBOR floating point wrapper object. See also Floating Point Numbers.
ParameterTypeDescription
valueNumberFloating point number to be wrapped.
ReturnsDescription
CBOR.FloatWrapper object.
2.3.1.  CBOR.Float Methods
2.3.1.1.  getFloat16()
SyntaxgetFloat16()
DescriptionGet CBOR floating point value.
Note: the CBOR object must be a 16-bit IEEE-754 item, otherwise an exception will be thrown.
ReturnsDescription
NumberDecoded floating point number.
2.3.1.2.  getFloat32()
SyntaxgetFloat32()
DescriptionGet CBOR floating point value.
Note: the CBOR object must be a 16-bit or 32-bit IEEE-754 item, otherwise an exception will be thrown.
ReturnsDescription
NumberDecoded floating point number.
2.3.1.3.  getFloat64()
SyntaxgetFloat64()
DescriptionGet CBOR floating point value.
ReturnsDescription
NumberDecoded floating point number.
2.3.2.  CBOR.Float Properties
2.3.2.1.  length
NameTypeDescription
lengthNumberLength in bytes of the underlying CBOR IEEE 754 type.
2.4.  CBOR.String
SyntaxCBOR.String(textString)
DescriptionConstructor. Creates a CBOR text string wrapper object.
ParameterTypeDescription
textStringStringString to be wrapped.
ReturnsDescription
CBOR.StringWrapper object.
2.4.1.  CBOR.String Methods
2.4.1.1.  getString()
SyntaxgetString()
DescriptionGet CBOR text string.
ReturnsDescription
StringDecoded text string.
2.5.  CBOR.Bytes
SyntaxCBOR.Bytes(byteString)
DescriptionConstructor. Creates a CBOR byte string wrapper object.
ParameterTypeDescription
byteStringUint8ArrayBinary data to be wrapped.
ReturnsDescription
CBOR.BytesWrapper object.
2.5.1.  CBOR.Bytes Methods
2.5.1.1.  getBytes()
SyntaxgetBytes()
DescriptionGet CBOR byte string.
ReturnsDescription
Uint8ArrayDecoded byte string.
2.6.  CBOR.Boolean
SyntaxCBOR.Boolean(value)
DescriptionConstructor. Creates a CBOR boolean wrapper object.
ParameterTypeDescription
valueBooleanBoolean to be wrapped.
ReturnsDescription
CBOR.BooleanWrapper object.
2.6.1.  CBOR.Boolean Methods
2.6.1.1.  getBoolean()
SyntaxgetBoolean()
DescriptionGet CBOR boolean.
ReturnsDescription
BooleanDecoded boolean.
2.7.  CBOR.Null
SyntaxCBOR.Null()
DescriptionConstructor. Creates a CBOR null wrapper object. See also isNull().
ReturnsDescription
CBOR.NullWrapper object.
2.8.  CBOR.Array
SyntaxCBOR.Array()
DescriptionConstructor. Creates an empty CBOR array wrapper object.
ReturnsDescription
CBOR.ArrayWrapper object.
2.8.1.  CBOR.Array Methods
2.8.1.1.  add()
Syntaxadd(object)
DescriptionAdd CBOR wrapper object to the array.
ParameterTypeDescription
objectCBOR.WrapperObject to be appended to the array.
ReturnsDescription
thisCurrent object.
2.8.1.2.  get()
Syntaxget(index)
DescriptionGet CBOR wrapper object from array. If index is out of range, an exception is thrown.
ParameterTypeDescription
indexNumberIndex (0..length-1) of object.
ReturnsDescription
CBOR.WrapperRetrieved object.
2.8.1.3.  toArray()
SyntaxtoArray()
DescriptionCopy array.
ReturnsDescription
[...]JavaScript array holding a copy of current CBOR.Wrapper objects.
2.8.2.  CBOR.Array Properties
2.8.2.1.  length
NameTypeDescription
lengthNumberNumber of objects in the array.
2.9.  CBOR.Map
SyntaxCBOR.Map()
DescriptionConstructor. Creates an empty CBOR map wrapper object.
ReturnsDescription
CBOR.MapWrapper object.
2.9.1.  CBOR.Map Methods
2.9.1.1.  set()
Syntaxset(key, value)
DescriptionSet map entry. If key entry is already defined, an exception is thrown.
Note: key order is of no importance since Deterministic Encoding performs the required map sorting automatically. See also setSortingMode() and CBOR.initDecoder().
ParameterTypeDescription
keyCBOR.WrapperKey (name) wrapper object.
valueCBOR.WrapperValue wrapper object.
ReturnsDescription
thisCurrent object.
2.9.1.2.  get()
Syntaxget(key)
DescriptionGet map entry. If key entry is undefined, an exception is thrown.
ParameterTypeDescription
keyCBOR.WrapperKey (name) wrapper object.
ReturnsDescription
CBOR.WrapperRetrieved object.
2.9.1.3.  getConditional()
SyntaxgetConditional(key, defaultValue)
DescriptionGet map entry conditionally.
ParameterTypeDescription
keyCBOR.WrapperKey (name) wrapper object.
defaultValueCBOR.WrapperValue to return if key entry is undefined.
Note: defaultValue may be null.
ReturnsDescription
CBOR.WrapperRetrieved or default object.
2.9.1.4.  containsKey()
SyntaxcontainsKey(key)
DescriptionCheck map for key presence.
ParameterTypeDescription
keyCBOR.WrapperKey (name) wrapper object.
ReturnsDescription
Booleantrue or false.
2.9.1.5.  remove()
Syntaxremove(key)
DescriptionRemove map entry. If key entry is undefined, an exception is thrown.
ParameterTypeDescription
keyCBOR.WrapperKey (name) wrapper object.
ReturnsDescription
CBOR.WrapperRemoved object (value component).
2.9.1.6.  getKeys()
SyntaxgetKeys()
DescriptionGet map keys.
ReturnsDescription
[...]JavaScript array holding a copy of current CBOR.Wrapper map keys.
2.9.1.7.  setSortingMode()
SyntaxsetSortingMode(preSortedKeys)
DescriptionSet the sorting mode of the CBOR.Map() object during set() operations.
Typical usage:
let map = CBOR.Map().setSortingMode(true)
This method may be called multiple times which could be useful if you have a moderate set of unsorted meta data keys combined with a sorted large table-like set of keys. Note that this method has no effect on decoding operations.
ParameterTypeDescription
preSortedKeysBooleanIf true, keys must be provided in (CBOR wise) ascending order which can improve performance for maps having a huge number of keys. Improper key order will cause an exception to be thrown. By default map keys are sorted internally.
ReturnsDescription
thisCurrent object.
2.9.2.  CBOR.Map Properties
2.9.2.1.  length
NameTypeDescription
lengthNumberNumber of map entries.
2.10.  CBOR.Tag
SyntaxCBOR.Tag(tagNumber, object)
DescriptionConstructor. Creates a CBOR tag wrapper object.
ParameterTypeDescription
tagNumberBigIntTag number.
objectCBOR.WrapperObject to be wrapped in a tag.
ReturnsDescription
CBOR.TagWrapper object.
2.10.1.  CBOR.Tag Methods
2.10.1.1.  getTagNumber()
SyntaxgetTagNumber()
DescriptionGet CBOR tag number.
ReturnsDescription
BigIntDecoded tag number.
2.10.1.2.  getTaggedObject()
SyntaxgetTaggedObject()
DescriptionGet tagged CBOR object.
ReturnsDescription
CBOR.WrapperRetrieved object.

3.  Common Wrapper Methods

The CBOR wrapper objects support a set of common methods, described in this sub section.
3.1.  encode()
Syntaxencode()
DescriptionEncode this object.
Note: this method always return CBOR data using Deterministic Encoding.
ReturnsDescription
Uint8ArrayCBOR encoded data.
3.2.  clone()
Syntaxclone()
DescriptionCreate a new instance of this object, initialized with the original CBOR content.
ReturnsDescription
CBOR.WrapperDeep copy of this object.
3.3.  equals()
Syntaxequals(object)
DescriptionCompare this object with another object with respect to CBOR data.
ParameterTypeDescription
objectCBOR.WrapperThe object to compare with.
ReturnsDescription
Booleantrue if this object is equal to object, otherwise false.
3.4.  toDiag()
SyntaxtoDiag(prettyPrint)
DescriptionRender this object in Diagnostic Notation. In similarity to encode(), this method always produce data in Deterministic Encoding, irrespective to how the data was created. See also: toString().
ParameterTypeDescription
prettyPrintBooleanIf prettyPrint is true, additional white space is inserted between individual objects in maps and arrays, to make the result easier to read.
ReturnsDescription
StringTextual version of the wrapped CBOR content.
3.5.  toString()
SyntaxtoString()
DescriptionRender this object in Diagnostic Notation. Equivalent to calling toDiag() with a true argument.
ReturnsDescription
StringTextual version of the wrapped CBOR content.
3.6.  isNull()
SyntaxisNull()
DescriptionCheck for CBOR null.
Note: if checkForUnread() is used, this object will only be regarded as "read" if it actually is a CBOR null item.
See also CBOR.Null().
ReturnsDescription
BooleanReturns true if this object holds a CBOR null item, otherwise false is returned.
3.7.  checkForUnread()
SyntaxcheckForUnread()
DescriptionCheck if this object including possible child objects has been read (like calling getInt()). If any of the associated objects have not been read, an exception will be thrown.
The purpose of this method is to detect possible misunderstandings between parties using CBOR based protocols. Together with the strict type checking performed by the CBOR.js API, a programmatic counterpart to schema based processing can be achieved.
Note that array get(), map get(), and tag getTaggedObject() only locate objects, and thus do not count as "read".
Note that empty array and map objects are excluded from this check.
See also scan().
ReturnsDescription
thisCurrent object.
3.8.  scan()
Syntaxscan()
DescriptionScan this object as well as possible child objects in order to make them appear as "read". This is only meaningful in conjunction with checkForUnread().
ReturnsDescription
thisCurrent object.

4.  Decoding CBOR

CBOR decoding comes in two flavors, binary and Diagnostic Notation. Both decoders return the result as CBOR wrapper objects. This section lists the decoder methods.
4.1.  CBOR.decode()
SyntaxCBOR.decode(cbor)
DescriptionDecode a CBOR object.
This method is equivalent to CBOR.initDecoder(cbor).decodeWithOptions()
ParameterTypeDescription
cborUint8ArrayCBOR binary data holding exactly one CBOR object.
ReturnsDescription
CBOR.WrapperCBOR wrapper object.
4.2.  CBOR.initDecoder()
SyntaxCBOR.initDecoder(cbor)
DescriptionCreate a CBOR decoder supporting options. This decoding method presumes that the actual decoding is performed by one or more (for sequences only) calls to Decoder.decodeWithOptions().
ParameterTypeDescription
cborUint8ArrayThe CBOR data (bytes) to be decoded.
ReturnsDescription
DecoderDecoder object for optional use by the Decoder.set*() methods and finally used by Decoder.decodeWithOptions().
4.3.  Decoder.setDeterministicMode()
SyntaxDecoder.setDeterministicMode(enforce)
DescriptionSet CBOR decoder deterministic mode.
By default the decoder assumes that CBOR data conforms to the Deterministic Encoding rules. This method enables overriding the default.
ParameterTypeDescription
enforceBooleanIf the enforce flag is set to false, the decoder will accept CBOR data that does not adhere to the map sorting and preferred number serialization requirements. This option may be needed for dealing with "legacy" CBOR implementations. Note: duplicate keys and other invalid (or not supported) CBOR constructs will still cause an exception to be thrown.
ReturnsDescription
thisUpdated Decoder object.
4.4.  Decoder.setSequenceMode()
SyntaxDecoder.setSequenceMode(sequence)
DescriptionSet CBOR decoder sequence mode.
By default the decoder assumes that CBOR data constitutes of a single CBOR object. This method enables overriding the default.
ParameterTypeDescription
sequenceBooleanIf the sequence flag is set to true, the following apply:
  • Immediately return after decoding a CBOR object, while preparing the decoder for the next item. See also Decoder.getByteCount().
  • If no data is found (EOF), null is returned (empty sequences are permitted).
  • Note that data succeeding a just decoded CBOR object is not verified for correctness.
ReturnsDescription
thisUpdated Decoder object.
4.5.  Decoder.setNaNSupport()
SyntaxDecoder.setNaNSupport(accept)
DescriptionSet CBOR decoder NaN/Infinity support.
By default the decoder supports NaN, Infinity, and -Infinity. In case these variants are not applicable for the application in question, this method enables overriding the default.
ParameterTypeDescription
acceptBooleanIf the accept flag is set to false, the mentioned exceptional floating point values will cause an exception to be thrown.
ReturnsDescription
thisUpdated Decoder object.
4.6.  Decoder.decodeWithOptions()
SyntaxDecoder.decodeWithOptions()
DescriptionDecode CBOR data with options.
ReturnsDescription
CBOR.WrapperCBOR wrapper object or null (for EOF sequences only).
4.7.  Decoder.getByteCount()
SyntaxDecoder.getByteCount()
DescriptionGet decoder byte count.
This is equivalent to the position of the next item to be read.
ReturnsDescription
NumberThe number of bytes read so far.
4.8.  CBOR.diagDecode()
SyntaxCBOR.diagDecode(cborText)
DescriptionDecode a CBOR object provided in Diagnostic Notation. See also CBOR.diagDecodeSequence().
Note: this method always returns CBOR data using Deterministic Encoding.
ParameterTypeDescription
cborTextStringCBOR in textual format.
ReturnsDescription
CBOR.WrapperCBOR wrapper object.
4.9.  CBOR.diagDecodeSequence()
SyntaxCBOR.diagDecodeSequence(cborText)
DescriptionDecode a CBOR object provided in Diagnostic Notation. Unlike CBOR.diagDecode(), this method also accepts CBOR sequences, using a comma character (',') as a separator.
ParameterTypeDescription
cborTextStringCBOR in textual format.
ReturnsDescription
[...]Array holding one or more CBOR wrapper objects.

5.  Utility Methods

The following utility methods are unrelated to CBOR but have been included here because they are a part of the current CBOR.js implementation.
5.1.  CBOR.addArrays()
SyntaxCBOR.addArrays(a, b)
DescriptionAdd two arrays.
ParameterTypeDescription
aUint8ArrayFirst array.
bUint8ArraySecond array.
ReturnsDescription
Uint8ArrayConcatenation of array a and b.
5.2.  CBOR.compareArrays()
SyntaxCBOR.compareArrays(a, b)
DescriptionCompare two arrays lexicographically.
ParameterTypeDescription
aUint8ArrayFirst array.
bUint8ArraySecond array.
ReturnsDescription
NumberIf a and b are identical, 0 is retuned. If a > b, a positive number is returned. If a < b, a negative number is returned.
5.3.  CBOR.toHex()
SyntaxCBOR.toHex(byteArray)
DescriptionEncode binary data to hexadecimal.
ParameterTypeDescription
byteArrayUint8ArrayZero or more bytes to be encoded.
ReturnsDescription
StringHexadecimal encoded data.
5.4.  CBOR.fromHex()
SyntaxCBOR.fromHex(hexString)
DescriptionDecode hexadecimal data into binary.
ParameterTypeDescription
hexStringStringString with zero or more hexadecimal pairs. Each pair represents one byte.
ReturnsDescription
Uint8ArrayThe resulting binary (bytes).
5.5.  CBOR.toBase64Url()
SyntaxCBOR.toBase64Url(byteArray)
DescriptionEncode binary data to base64Url.
ParameterTypeDescription
byteArrayUint8ArrayZero or more bytes to be encoded.
ReturnsDescription
StringBase64Url encoded data.
5.6.  CBOR.fromBase64Url()
SyntaxCBOR.fromBase64Url(base64)
DescriptionDecode base64Url encoded data into binary. Note that this method is permissive; it accepts base64 encoded data as well as data with or without '=' padding.
ParameterTypeDescription
base64StringString in base64Url notation. The string may be empty.
ReturnsDescription
Uint8ArrayThe resulting binary (bytes).

6.  JavaScript Number Considerations

Since JavaScript natively only supports Number (backed by 64-bit IEEE 754 floating point data), and BigInt (offering unlimited integers), it is important to understand how these number types are mapped to CBOR which offers two variants of integers and three variants of floating point types.
6.1.  Integer Numbers
Due to the Number.MAX_SAFE_INTEGER limitation, CBOR protocols using integer objects where the magnitude may exceed 253-1, must for such objects turn to BigInt, otherwise run-time errors may occur when accessing integer data using getInt() or during creation of integers using CBOR.Int(). That is, for creation of such integers, CBOR.BigInt() is the proper solution, while access requires getBigInt(), which for convenience reasons is supported by both of the integer wrapper types.

Note that selecting CBOR.BigInt() or CBOR.Int() only affects the maximum numeric range with respect to JavaScript limits, not the CBOR encoding. During CBOR decoding, the selection between CBOR.BigInt() and CBOR.Int() is governed by the decoded value with respect to JavaScript limits.

The selection between the CBOR unsigned and negative integer variants is dealt with by the CBOR.js implementation; transparent to the API.

6.2.  Floating Point Numbers
Although CBOR encoding depends on 16, 32, and 64-bit IEEE 754 variants, the CBOR.js implementation makes this transparent. The CBOR.Float() wrapper object only exposes the JavaScript Number type.

See also the Decoder.setNaNSupport() decoder method.

7.  Diagnostic Notation

Creating CBOR data in diagnostic notation (as described in section 8 of RFC 8949), is provided by the toString() method.

However, through the CBOR.diagDecode() method, CBOR data may also be provided in diagnostic (textual) notation, making CBOR useful for local "config" and test data files as well.

Due to the Deterministic Encoding scheme used by CBOR.js, CBOR data can be bidirectionally converted between its native (binary) format and diagnostic notation without getting corrupted. Note though that text-binary-text "roundtrips" do not necessarily return identical text: 0x10 used as diagnostic notation input will return 16 as diagnostic notation output.

The following table shows how CBOR objects should be represented in diagnostic notation:
CBOR ObjectSyntaxNotesDescription
/ comment text / 7 Multi-line comment. Multi-line comments are treated as whitespace and may thus also be used between CBOR objects.
# comment text 7 Single-line comment. Single-line comments are terminated by a newline character ('\n') or EOF. Single-line comments may also terminate lines holding regular CBOR items.
integer {sign}{0b|0o|0x}n 1, 2 Arbitrary sized integers without fractional components or exponents. See also CBOR integer encoding.
For input data in diagnostic notation, binary, octal, and hexadecimal notation is also supported by prepending numbers with 0b, 0o, and 0x respectively. The latter also permit arbitrary insertions of '_' characters between digits to enable grouping of data like 0b100_000000001.
bignum
floating point {sign}n.n{n} 1, 2 Floating point values must include a decimal point and an optional exponent. See also CBOR floating point encoding.
NaN Not a number. See also CBOR floating point encoding.
{sign}Infinity 2 Infinity. See also CBOR floating point encoding.
byte string h'hex data' 3, 6 Byte data provided in hexadecimal notation. Each byte must be represented by two hexadecimal digits.
b64'base64 data' 3, 6, 7 Byte data provided in base64 or base64URL notation. Padding with '=' characters is optional.
'text' 4, 5, 7 Byte data provided as UTF-8 encoded text.
<< object >> 7 Construct holding a CBOR object which is subsequently embedded in a byte string.
text string "text" 4, 5 UTF-8 encoded text string.
true true Boolean value.
falsefalse
null null Null value.
array [ objects ] Array with zero or more comma separated CBOR objects.
map { key:value } Map with zero or more comma separated key/value pairs. Keys and values are expressed as CBOR objects.
tag n( object ) 1 Tag holding a CBOR object.
, 7 Separator character for CBOR sequences.
  1. The letter n in the Syntax column denotes one or more digits.
  2. The optional {sign} must be a single hyphen ('-') character.
  3. Input only: the whitespace characters (' ', '\t', '\r', '\n') inside of string quotes are ignored.
  4. Input only: the control characters ('\t' and '\n') inside of string quotes become a part of the text. For nomalizing line terminators, a single '\r' or the combination '\r\n' are rewritten as '\n'. To avoid getting newline characters ('\n') included in multi-line text strings, a line continuation marker consisting of a backslash ('\') immediately preceding the newline may be used.
  5. Text strings may also include JavaScript compatible escape sequences ('\'', '\"', '\\', '\b', '\f', '\n', '\r', '\t', '\uhhhh').
  6. Zero-length strings ('') return byte strings of length zero.
  7. Input only: the toString() method does not produce this item.

8.  Deterministic Encoding

This section is primarily targeting implementers of CBOR tools.

While there are different ways you can encode certain CBOR objects, this is non-trivial to support in a generic platform API without adding complexity and that for little provable gain. Therefore the CBOR.js API defines specific (non-variant) encodings, aka "Deterministic Encoding". The chosen encoding model is compatible with most existing CBOR decoders.

However, to not limit CBOR.js to new applications only, deterministic encoding checking may optionally be turned off for accepting input from "legacy" CBOR encoders.

The encoding scheme adheres to section 4.2 of RFC 8949, but adds a few constraints (denoted by RFC+), where the RFC offers choices. The encoding rules are as follows:

9.  Using the CBOR API

This section provides a few examples on how to use the CBOR API.
9.1.  Encode CBOR
The following code shows how you can create CBOR-encoded data:
let cbor = CBOR.Map()
               .set(CBOR.Int(1), CBOR.Float(45.7))
               .set(CBOR.Int(2), CBOR.String("Hi there!")).encode();

console.log(CBOR.toHex(cbor));
--------------------------------------------
a201fb4046d9999999999a0269486920746865726521
9.2.  Decode CBOR
The following code shows how you can decode CBOR-encoded data, here using the result of the encoding example:
let map = CBOR.decode(cbor);
console.log(map.toString());  // Diagnostic notation
----------------------------------------------------
{
  1: 45.7,
  2: "Hi there!"
}

console.log('Value=' + map.get(CBOR.Int(1)));
---------------------------------------------
Value=45.7
9.3.  Using Diagnostic Notation
The following code shows how you can decode CBOR specified in Diagnostic Notation:
let cbor = CBOR.diagDecode(`{
# Comments are also permitted
  1: 45.7,
  2: "Hi there!"
}`).encode();

console.log(CBOR.toHex(cbor));
------------------------------
a201fb4046d9999999999a0269486920746865726521

10.  Version

API version: 1.0.9. Note that the current API version is accessible through the static property CBOR.version.
Document version: 2024-10-17