Flattening Nested JSON Into Dot-Notation Keys
Turn deeply nested JSON into a single-level object with keys like address.geo.lat, and turn it back again. fx runs plain JavaScript on the input, so a short recursive function covers both directions. Install fx first.
Flatten Nested JSON to Dot Notation
Walk every object and array, joining keys with .. Array indexes become path segments (roles.0):
fx user.json 'x => {
const flat = (v, p) => v && typeof v === "object" && Object.keys(v).length
? Object.entries(v).flatMap(([k, val]) => flat(val, p ? p + "." + k : k))
: [[p, v]];
return Object.fromEntries(flat(x, ""));
}'Input:
{
"id": 42,
"name": "Alice",
"address": {
"city": "Berlin",
"geo": {"lat": 52.52, "lng": 13.4}
},
"roles": ["admin", "editor"],
"settings": {"theme": "dark", "notifications": {"email": true, "sms": false}}
}Output:
{
"id": 42,
"name": "Alice",
"address.city": "Berlin",
"address.geo.lat": 52.52,
"address.geo.lng": 13.4,
"roles.0": "admin",
"roles.1": "editor",
"settings.theme": "dark",
"settings.notifications.email": true,
"settings.notifications.sms": false
}Empty objects and arrays have no leaves, so they are kept as they are ("user.tags": [], "meta": {}).
Flatten JSON With a Custom Separator
Replace "." with any string, for example _ for environment-variable style keys:
echo '{"db": {"host": "localhost", "ports": [5432, 5433]}}' | fx 'x => {
const flat = (v, p) => v && typeof v === "object" && Object.keys(v).length
? Object.entries(v).flatMap(([k, val]) => flat(val, p ? p + "_" + k : k))
: [[p, v]];
return Object.fromEntries(flat(x, ""));
}'Output:
{
"db_host": "localhost",
"db_ports_0": 5432,
"db_ports_1": 5433
}Unflatten Dot-Notation JSON Back to Nested Objects
Split each key on . and rebuild the tree. A numeric next segment creates an array instead of an object:
echo '{"user.name": "Alice", "user.langs.0": "Go", "user.langs.1": "JS", "active": true}' | fx 'x => {
const out = {};
for (const [path, v] of Object.entries(x)) {
const keys = path.split(".");
let cur = out;
keys.forEach((k, i) => {
if (i === keys.length - 1) cur[k] = v;
else cur = cur[k] ??= /^\d+$/.test(keys[i + 1]) ? [] : {};
});
}
return out;
}'Output:
{
"user": {
"name": "Alice",
"langs": [
"Go",
"JS"
]
},
"active": true
}Run on the output of the first section, it gives back the original user.json.
Save flat and unflat as Reusable Functions
Put both functions in .fxrc.js in the current directory, your home directory, or the XDG config directory:
function flat(x, sep = ".") {
const walk = (v, p) => v && typeof v === "object" && Object.keys(v).length
? Object.entries(v).flatMap(([k, val]) => walk(val, p ? p + sep + k : k))
: [[p, v]]
return Object.fromEntries(walk(x, ""))
}
function unflat(x, sep = ".") {
const out = {}
for (const [path, v] of Object.entries(x)) {
const keys = path.split(sep)
let cur = out
keys.forEach((k, i) => {
if (i === keys.length - 1) cur[k] = v
else cur = cur[k] ??= /^\d+$/.test(keys[i + 1]) ? [] : {}
})
}
return out
}Now they work like built-ins:
fx user.json flat # same output as the first section
fx user.json 'x => flat(x, "_")' # custom separator
fx user.json flat unflat # round trip, prints user.json unchanged
cat config.yaml | fx --yaml flat # YAML works too, keys like "database.pool.max"Flatten Each Object in a JSON Array
Use @ to apply flat to every record. Nested fields become columns, ready for CSV export:
fx orders.json '@flat(x)' '[keys(x[0]), ...x.map(values)]' '@.join(",")' listInput:
[
{"id": "A-1001", "customer": {"name": "Alice", "email": "alice@example.com"}, "total": {"amount": 59.9, "currency": "EUR"}},
{"id": "A-1002", "customer": {"name": "Bob", "email": "bob@example.com"}, "total": {"amount": 12.5, "currency": "USD"}},
{"id": "A-1003", "customer": {"name": "Carol", "email": "carol@example.com"}, "total": {"amount": 230, "currency": "EUR"}}
]Output:
id,customer.name,customer.email,total.amount,total.currency
A-1001,Alice,alice@example.com,59.9,EUR
A-1002,Bob,bob@example.com,12.5,USD
A-1003,Carol,carol@example.com,230,EURfx orders.json '@flat(x)' alone prints the array of flattened objects.
WARNING
Do not write map(flat). map passes the index as the second argument, which becomes the separator, and you get keys like customer0name. Use @flat(x) or map(x => flat(x)).
Flatten Nested Arrays (Arrays of Arrays)
Flattening an array of arrays is a different operation: it merges the inner arrays into one list. The built-in flatten removes one level:
echo '[[1, 2], [3, [4, 5]], [6]]' | fx flatten[
1,
2,
3,
[
4,
5
],
6
].[] does the same. To flatten all levels, use JavaScript's .flat(Infinity):
echo '[[1, 2], [3, [4, 5]], [6]]' | fx '.flat(Infinity)'[
1,
2,
3,
4,
5,
6
]