Number Precision and Formatting in JSON vs YAML
Understand how JSON and YAML handle large numbers, floating-point precision, special numeric values, and different number formats like octal and hexadecimal.
Detailed Explanation
Numbers are handled similarly in JSON and YAML for common cases, but edge cases around precision, special values, and alternative formats can cause conversion issues.
Basic numbers (identical in both formats):
{ "integer": 42, "negative": -17, "float": 3.14 }
integer: 42
negative: -17
float: 3.14
Large integers and precision loss:
big_id: 9007199254740993
timestamp_ns: 1705312200000000000
JavaScript's Number.MAX_SAFE_INTEGER is 9007199254740991. Numbers larger than this lose precision when parsed in JavaScript. Both JSON and YAML suffer from this limitation in JavaScript environments. The value 9007199254740993 may become 9007199254740992 after parsing.
YAML-specific number formats (not available in JSON):
# Octal (YAML 1.1 uses 0-prefix, YAML 1.2 uses 0o-prefix)
file_perms_v1: 0755 # YAML 1.1: decimal 493
file_perms_v2: 0o755 # YAML 1.2: decimal 493
# Hexadecimal
color: 0xFF5733 # decimal 16734003
# Infinity and NaN (YAML supports, JSON does not)
max_value: .inf
min_value: -.inf
undefined_result: .nan
Converted to JSON:
{
"file_perms_v1": 493,
"file_perms_v2": 493,
"color": 16734003,
"max_value": null,
"min_value": null,
"undefined_result": null
}
Critical differences:
- Octal numbers (
0755) in YAML are converted to their decimal equivalent in JSON. If you meant the string"0755"(like a file permission), you must quote it. .infand.nanhave no JSON equivalent. They are typically converted tonullor cause an error, depending on the converter.- Underscores in numbers are allowed in YAML for readability (
1_000_000) but not in JSON. - Scientific notation works in both:
1.5e10is valid JSON and YAML.
When precision matters, store large numbers as strings in both formats: "9007199254740993".
Use Case
Converting a configuration file containing Unix file permissions in octal notation (0755, 0644) between YAML and JSON while ensuring the numeric values are correctly interpreted and not corrupted.