Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can hex format be used with JSON files? If so, how?

Tags:

The following object is a valid one in plain Javascript. However, if the same is added to a JSON file, the file does not pass validation. Why is that?

var message = {     "senderID": [ 0x01 ],     "receiverID": [ 0xFF ],     "commandCode": [ 0x00, 0x05 ],     "payload": [ 0xFF ] } 
like image 410
Andrei Oniga Avatar asked Oct 05 '18 18:10

Andrei Oniga


People also ask

What is the correct format of a JSON file?

JSON Syntax RulesData is in name/value pairs. Data is separated by commas. Curly braces hold objects. Square brackets hold arrays.

What is the format and the use of JSON file?

A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server.

Which key format is valid in JSON?

In the JSON data format, the keys must be enclosed in double quotes. The key and value must be separated by a colon (:) symbol. There can be multiple key-value pairs. Two key-value pairs must be separated by a comma (,) symbol.

Which type are not supported by JSON?

JSON supports a value of type String, Number and Boolean. It does not support octal and hexdecimal values.


2 Answers

JSON does not support hexadecimal numbers but they are supported in JSON5. json5.org

like image 110
DESH Avatar answered Sep 20 '22 23:09

DESH


The JSON spec supports numbers as values but explicitly does not support octal or hexidecimal. This is in part to increase interchange between languages. You could just as easily represent 0xFF as a string, "0xFF" and parse that out when using it.


From json.org:

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

According to the ECMA-404 Final draft:

A number is a sequence of decimal digits with no superfluous leading zero. It may have a preceding minus sign (U+002D). It may have a fractional part prefixed by a decimal point (U+002E). It may have an exponent, prefixed by e (U+0065) or E (U+0045) and optionally + (U+002B) or – (U+002D). The digits are the code points U+0030 through U+0039.

The spec also explains why this is restriction is beneficial to both producer and consumer:

JSON is agnostic about the semantics of numbers. In any programming language, there can be a variety of number types of various capacities and complements, fixed or floating, binary or decimal. That can make interchange between different programming languages difficult. JSON instead offers only the representation of numbers that humans use: a sequence of digits. All programming languages know how to make sense of digit sequences even if they disagree on internal representations. That is enough to allow interchange.

like image 21
chazsolo Avatar answered Sep 18 '22 23:09

chazsolo