Json string number format

Viewed 256

I try to understand JSON strings better. Especially numbers in that format.

Checking if a JSON string is a valid number is easy (as described later), but what are the conventions for parsing a number to a JSON string?

The number 5 can be easily parsed to "5", but should I parse 5000 to "5000", to "5e3" or to "5E3"?

Is there a widely accepted (conventions?) minimum/maximum bound for numbers which are too small/too big such that we use e?

And a second question on this topic: how would I check if the JSON string stores an integer value. This question arises because "5e-2" is 0.05. The string doesn't contain "." but is still a fraction, which is non trivial. Of course I could do it with simply parsing the value with Number() (JavaScript) and checking if it is an integer with Number.isInteger() (JavaScript). But that doesn't help me to understand it really better. Could I check if the string contains "e-"/"E-", then check if the following number is bigger than the number of digits before the "."/"e"/"E"?

To check if a JSON string is a valid number (not integer), I use this regex in JavaScript:

// JavaScript
const isJsonNumberRegex = /^-?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?$/m;

function isJsonNumber(n: string): boolean {
    return n.match(isJsonNumberRegex) !== null;
}

The string can start with "-", then comes a single 0 or a digit 1-9, then optionally followed by any amount of digits 0-9. If it is a fraction, it is followed by a "." and then by any amount of digits 0-9. To use exponents it starts by the character "e" or "E", is optionally followed by "+" or "-", and then again any amount of digits 0-9.

For example:

function isJsonNumber(n){
    return n.match(/^-?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?$/m) !== null;
}

console.log(isJsonNumber("-12.34E+56")); // true
console.log(isJsonNumber("0.0e-010")); // true

console.log(isJsonNumber("+0")); // false
console.log(isJsonNumber(".5")); // false
console.log(isJsonNumber("a")); // false

1 Answers

The specification for JSON can be found here: https://datatracker.ietf.org/doc/html/rfc4627#section-2.4

Copy of what is said in the above link:

The representation of numbers is similar to that used in most programming languages. A number contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part.

Therefore, your test should work per these specifications.

Related