Null Representation in JSON vs YAML
Learn the different ways null values are represented in JSON and YAML. Covers null, ~, empty values, and how to ensure correct conversion between formats.
Detailed Explanation
Null values represent the intentional absence of a value. JSON has a single representation for null, while YAML offers multiple ways to express the same concept, which can cause confusion during conversion.
JSON null:
{
"middleName": null,
"nickname": null,
"age": null
}
YAML equivalents (all represent null):
middleName: null
nickname: ~
age:
All three YAML representations convert to the same JSON: null. The three styles are:
null-- Explicit, matching JSON's syntax. Most readable and unambiguous.~(tilde) -- YAML's shorthand for null. Common in Ruby ecosystem.- Empty value -- An empty value after the colon is also null. This is the most concise but least explicit.
Additional null-like strings parsed as null in YAML 1.1:
a: Null
b: NULL
c: ~
d:
All of these produce null in JSON output.
Empty strings vs null -- a critical distinction:
# This is null
value1:
# This is an empty string
value2: ""
# This is the literal string "null"
value3: "null"
Converts to JSON:
{
"value1": null,
"value2": "",
"value3": "null"
}
When converting JSON to YAML, a null value can be rendered in any of the three styles. Most converters use the explicit null keyword for clarity. When converting YAML to JSON, ensure your parser correctly distinguishes between empty strings and null values -- this is a common source of bugs in configuration files.
Best practice: Always use the explicit null keyword in YAML when you mean null, and always quote strings that might look like null ("null", "~", "").
Use Case
Defining optional fields in a user profile configuration where some fields like middle name or phone number may intentionally have no value, and ensuring the nulls survive round-trip conversion.