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.  update()
n/a2.8.1.4.  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.  merge()
n/a2.9.1.3.  update()
n/a2.9.1.4.  get()
n/a2.9.1.5.  getConditional()
n/a2.9.1.6.  containsKey()
n/a2.9.1.7.  remove()
n/a2.9.1.8.  getKeys()
n/a2.9.1.9.  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.  get()
n/a2.10.1.3.  update()
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.decodeWithOptions()
n/a4.4.  Decoder.getByteCount()
n/a4.5.  CBOR.diagDecode()
n/a4.6.  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 (here expressed in CDDL [RFC8610link] notation) supported by this specification:
CBORWrapper ObjectJavaScriptNotes
int CBOR.Int Number 1
bigint CBOR.BigInt BigInt 1
float CBOR.Float Number 2
bstr CBOR.Bytes Uint8Array
tstr CBOR.String String
bool 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 bool, null, and float.

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 object.
See also Integer Numbers.
ParameterTypeDescription
valueNumberInteger to be wrapped.
Note that a non-integer value causes an exception to be thrown.
ReturnsDescription
CBOR.IntObject.
2.1.1.  CBOR.Int Methods
2.1.1.1.  getInt()
SyntaxgetInt()
DescriptionGet CBOR integer.
Values outside of -253+1 to 253-1 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 cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.3.  getUint8()
SyntaxgetUint8()
DescriptionGet CBOR integer.
Values outside of 0 to 0xff cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.4.  getInt16()
SyntaxgetInt16()
DescriptionGet CBOR integer.
Values outside of -0x8000 to 0x7fff cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.5.  getUint16()
SyntaxgetUint16()
DescriptionGet CBOR integer.
Values outside of 0 to 0xffff cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.6.  getInt32()
SyntaxgetInt32()
DescriptionGet CBOR integer.
Values outside of -0x80000000 to 0x7fffffff cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.7.  getUint32()
SyntaxgetUint32()
DescriptionGet CBOR integer.
Values outside of 0 to 0xffffffff cause an exception to be thrown.
ReturnsDescription
NumberDecoded integer.
2.1.1.8.  getInt64()
SyntaxgetInt64()
DescriptionGet CBOR integer.
Values outside of -0x8000000000000000 to 0x7fffffffffffffff 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 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 object.
See also Integer Numbers.
ParameterTypeDescription
valueBigIntBig integer to be wrapped.
ReturnsDescription
CBOR.BigIntObject.
2.2.1.  CBOR.BigInt Methods
2.2.1.1.  getInt64()
SyntaxgetInt64()
DescriptionGet CBOR integer.
Values outside of -0x8000000000000000 to 0x7fffffffffffffff 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 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 float object. See also Floating-Point Numbers.
ParameterTypeDescription
valueNumberFloating-point number to be wrapped.
ReturnsDescription
CBOR.FloatObject.
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 (tstr) object.
ParameterTypeDescription
textStringStringString to be wrapped.
ReturnsDescription
CBOR.StringObject.
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 (bstr) object.
ParameterTypeDescription
byteStringUint8ArrayBinary data to be wrapped.
ReturnsDescription
CBOR.BytesObject.
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 (bool) object.
ParameterTypeDescription
valueBooleanBoolean to be wrapped.
ReturnsDescription
CBOR.BooleanObject.
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 object. See also isNull().
ReturnsDescription
CBOR.NullObject.
2.8.  CBOR.Array
SyntaxCBOR.Array()
DescriptionConstructor. Creates an empty CBOR array object.
ReturnsDescription
CBOR.ArrayObject.
2.8.1.  CBOR.Array Methods
2.8.1.1.  add()
Syntaxadd(object)
DescriptionAdd CBOR 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 object at a specific position in the array. If index is out of range, an exception is thrown.
ParameterTypeDescription
indexNumberIndex (0..length-1) of array.
Note that a non-integer index causes an exception to be thrown.
ReturnsDescription
CBOR.WrapperRetrieved object.
2.8.1.3.  update()
Syntaxupdate(index, object)
DescriptionUpdate CBOR object at a specific position in the array. If index is out of range, an exception is thrown.
ParameterTypeDescription
indexNumberIndex (0..length-1) of array.
Note that a non-integer index causes an exception to be thrown.
objectCBOR.WrapperUpdate object.
ReturnsDescription
CBOR.WrapperPrevious object.
2.8.1.4.  toArray()
SyntaxtoArray()
DescriptionCopy array.
ReturnsDescription
[CBOR.Wrapper...]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 object.
ReturnsDescription
CBOR.MapObject.
2.9.1.  CBOR.Map Methods
2.9.1.1.  set()
Syntaxset(key, object)
DescriptionSet map entry. If key 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().
Note: this implementation presumes that key objects are immutable. That is, the following code will throw an exception:
let key = CBOR.Array();
let map = CBOR.Map().set(key, CBOR.Int(5));
key.add(CBOR.String("data")); // Mutating key object
By defining key objects inline (chaining) or by preset variable declarations, key objects of any complexity can be used.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
objectCBOR.WrapperObject (value).
ReturnsDescription
thisCurrent object.
2.9.1.2.  merge()
Syntaxmerge(map)
DescriptionMerge maps. Performs a set() operation for each member of the map argument.
ParameterTypeDescription
mapCBOR.MapCBOR map wrapper object.
ReturnsDescription
thisCurrent object.
2.9.1.3.  update()
Syntaxupdate(key, object, existing)
DescriptionUpdate map entry.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
objectCBOR.WrapperObject (value).
existingBooleanIf existing is true, key must be defined, else an exception is thrown.
If existing is false, a map entry will be created for key if not already defined.
ReturnsDescription
CBOR.WrapperPrevious object. May be null.
2.9.1.4.  get()
Syntaxget(key)
DescriptionGet map entry. If key is undefined, an exception is thrown.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
ReturnsDescription
CBOR.WrapperRetrieved object.
2.9.1.5.  getConditional()
SyntaxgetConditional(key, defaultObject)
DescriptionGet map entry conditionally.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
defaultObjectCBOR.WrapperObject to return if key is undefined.
Note: defaultObject may be null.
ReturnsDescription
CBOR.WrapperRetrieved or default object.
2.9.1.6.  containsKey()
SyntaxcontainsKey(key)
DescriptionCheck map for key presence.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
ReturnsDescription
Booleantrue or false.
2.9.1.7.  remove()
Syntaxremove(key)
DescriptionRemove map entry. If key is undefined, an exception is thrown.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
ReturnsDescription
CBOR.WrapperRemoved object (value).
2.9.1.8.  getKeys()
SyntaxgetKeys()
DescriptionGet map keys.
ReturnsDescription
[CBOR.Wrapper...]JavaScript array holding a copy of current key objects.
2.9.1.9.  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 causes 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 object.
ParameterTypeDescription
tagNumberBigIntTag number.
objectCBOR.WrapperObject to be wrapped in a tag.
ReturnsDescription
CBOR.TagObject.
2.10.1.  CBOR.Tag Methods
2.10.1.1.  getTagNumber()
SyntaxgetTagNumber()
DescriptionGet CBOR tag number.
ReturnsDescription
BigIntDecoded tag number.
2.10.1.2.  get()
Syntaxget()
DescriptionGet tagged CBOR object.
ReturnsDescription
CBOR.WrapperRetrieved object.
2.10.1.3.  update()
Syntaxupdate(object)
DescriptionUpdate tagged CBOR object.
ParameterTypeDescription
objectCBOR.WrapperUpdate object.
ReturnsDescription
CBOR.WrapperPrevious 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 decoding can be achieved.
Note that array get(), map get(), and tag get() 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, 0).decodeWithOptions()
ParameterTypeDescription
cborUint8ArrayCBOR binary data holding exactly one CBOR object.
ReturnsDescription
CBOR.WrapperObject.
4.2.  CBOR.initDecoder()
SyntaxCBOR.initDecoder(cbor, options)
DescriptionCreate a customized CBOR decoder. 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.
optionsNumberThe decoder options. Multiple options can be combined using the binary OR-operator ("|"). A zero (0) sets the decoder default mode. The options are defined by the following constants:
CBOR.SEQUENCE_MODE:
If the CBOR.SEQUENCE_MODE option is defined, the following apply:
  • The decoder returns after having decoded a single CBOR object, while preparing for the next object.
    See also Decoder.getByteCount().
  • If no data is found (EOF), null is returned (empty sequences are permitted).
Note that data that has not yet been decoded, is not verified for correctness.
CBOR.LENIENT_MAP_DECODING:
By default, the decoder requires that CBOR maps conform to the Deterministic Encoding rules. The CBOR.LENIENT_MAP_DECODING option forces the decoder to accept CBOR maps with arbitrary key ordering. Note that duplicate keys still cause an exception to be thrown.
CBOR.LENIENT_NUMBER_DECODING:
By default, the decoder requires that CBOR numbers conform to the Deterministic Encoding rules.
The CBOR.LENIENT_NUMBER_DECODING option forces the decoder to accept different representations of CBOR int, bigint, and float items, only limited by RFC 8949.
CBOR.REJECT_INVALID_FLOATS:
By default, the decoder supports NaN and Infinity values. In case these variants are not applicable for the application in question, the CBOR.REJECT_INVALID_FLOATS option causes such numbers to throw an exception.
ReturnsDescription
DecoderDecoder object to be used with Decoder.decodeWithOptions().
4.3.  Decoder.decodeWithOptions()
SyntaxDecoder.decodeWithOptions()
DescriptionDecode CBOR data with options.
ReturnsDescription
CBOR.WrapperObject or null (for EOF sequences only).
4.4.  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.5.  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.WrapperObject.
4.6.  CBOR.diagDecodeSequence()
SyntaxCBOR.diagDecodeSequence(cborText)
DescriptionDecode CBOR objects 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
[CBOR.Wrapper...]JavaScript array holding one or more 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 using getBigInt(), getInt64(), or getUint64(), 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 CBOR.initDecoder() 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:
CBORSyntaxNotesDescription
/ 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.
int {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.
bigint
float {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.
bstr 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.
tstr "text" 4, 5 UTF-8 encoded text-string.
booltrue Boolean value.
false
null null Null value.
array [ object ] 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.
, 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: between the quotes, the whitespace characters (' ', '\t', '\r', '\n') 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 implements specific (non-variant) encodings, aka "Deterministic Encoding". The chosen encoding scheme is backward compatible with most existing CBOR decoders. However, for decoding (only), compliance with deterministic encoding rules may be relaxed, enabling the processing of CBOR data using "legacy" encoding schemes as well.

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.12. Note that the current API version is accessible through the static property CBOR.version.
Document version: 2025-02-16