cbor / cbor.github.io

cbor.io web site
75 stars 33 forks source link

Is the root element required to be a map or an array? #59

Closed jeremyherbert closed 4 years ago

jeremyherbert commented 4 years ago

In JSON, it seems to be expected that the root element is a map or an array. From reading the RFC for CBOR, I can’t find any mention of a requirement like this; ie, that a map or array is the first object which then holds other objects. Is this required and I just missed it? If not, what is the method to convert a CBOR stream without a map or array as the root object to JSON?

jeremyherbert commented 4 years ago

It looks like as of 2017, JSON doesn’t have this requirement anymore as per https://tools.ietf.org/html/rfc8259

A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array. Implementations that generate only objects or arrays where a JSON text is called for will be interoperable in the sense that all implementations will accept these as conforming JSON texts.

However, the CBOR RFC references https://tools.ietf.org/html/rfc4627 from 2006 which states explicitly that

A JSON text is a serialized object or array.

So I think this might be an error in the CBOR RFC as there cannot be a 1:1 mapping of CBOR to JSON (as per RFC 4627).

cabo commented 4 years ago

Hi Jeremy,

as you noticed, JSON is no longer limited to arrays and maps at the top level.

That decision was already in the air at the time CBOR was designed (2013); which may have been one reason we didn't address the outgoing restriction in RFC 7049 (which was approved in September 2013 and published in October 2013).
(Lifting the restriction formally was reflected in the JSON working draft draft-ietf-json-rfc4627bis-08.txt, around December 2013. RFC 7159, which was based on that, came out half a year after RFC 7049, so we could only reference RFC 4627 in RFC 7049.)

However, probably the main reason we didn't think of addressing the restriction is that the CBOR data model is more powerful than that of JSON, so a 1:1 mapping (that preserves all information) isn't possible in any case.

By the way, you may want to have a look at https://github.com/cbor-wg/CBORbis where the IETF CBOR WG works on an editorial revision of RFC 7049, to be published later this year.