Flatten nested JSON to one line per value
To flatten nested JSON on the command line, run gronify flatten file.json, or pipe JSON into gronify flatten. It prints one json.path = value line for every value, with array positions in brackets, so each value carries its full path and the output works with grep, sort, diff, and awk.
Updated
Flatten a JSON file or standard input
Install Gronify with npm install -g gronify on Node.js 20 or newer (install options). The examples on this page use a small service config saved as config.json:
cat config.json{"name":"api","port":8080,"debug":false,"owner":null,"tags":["web","eu"],"db":{"host":"db.internal","replicas":[{"host":"r1","lag":0.5},{"host":"r2","lag":1.25}]},"grid":[[1,2],[3,4]],"limits":{},"plugins":[]}gronify flatten config.jsonjson = {}json.name = "api"json.port = 8080json.debug = falsejson.owner = nulljson.tags = []json.tags[0] = "web"json.tags[1] = "eu"json.db = {}json.db.host = "db.internal"json.db.replicas = []json.db.replicas[0] = {}json.db.replicas[0].host = "r1"json.db.replicas[0].lag = 0.5json.db.replicas[1] = {}json.db.replicas[1].host = "r2"json.db.replicas[1].lag = 1.25json.grid = []json.grid[0] = []json.grid[0][0] = 1json.grid[0][1] = 2json.grid[1] = []json.grid[1][0] = 3json.grid[1][1] = 4json.limits = {}json.plugins = []Each object and array gets a line of its own, such as json.db = {}, ahead of the values inside it. Strings keep their JSON quotes, and numbers, true, false, and null print as they appear in the file. Lines follow the order of the document, and the file is read as a stream, so it is never loaded whole.
Leave out the file name and Gronify reads standard input. The root does not have to be an object:
echo '[1,[2,3],{"a":null}]' | gronify flattenjson = []json[0] = 1json[1] = []json[1][0] = 2json[1][1] = 3json[2] = {}json[2].a = nullHow arrays, nested arrays, and empty containers print
The two transcripts above contain every case but the last:
- An array element is its zero-based position in brackets:
json.tags[0], thenjson.tags[1]. - An array of objects prints one
= {}line per element, then that element's fields:json.db.replicas[0] = {}, thenjson.db.replicas[0].host. - A nested array stacks the brackets, outer position first:
json.grid[1][0] = 3is the first item of the second row. - An empty object or array is a single line,
json.limits = {}orjson.plugins = []. A container with children opens with the same line, so it is empty only when the next line does not extend its path. - A root array starts with
json = []and its elements arejson[0],json[1]. A document that is one string or number is one line, such asjson = "hello".
Keys with dots, spaces, quotes, or non-ASCII characters
A key is written bare after a dot only when it starts with an ASCII letter, _, or $ and continues with ASCII letters, digits, _, or $. Any other key goes in brackets as a JSON string:
cat keys.json{"a.b":1,"first name":2,"say \"hi\"":3,"naïve":4,"日本語":5,"":6,"123":7,"1st":8,"_ok":9,"$ref":10,"x-y":11}gronify flatten keys.jsonjson = {}json["a.b"] = 1json["first name"] = 2json["say \"hi\""] = 3json["naïve"] = 4json["日本語"] = 5json[""] = 6json["123"] = 7json["1st"] = 8json._ok = 9json.$ref = 10json["x-y"] = 11The brackets remove the ambiguity that dotted notation has. json["a.b"] is one key named a.b, while json.a.b is a key b inside an object a. json["123"] is an object key that looks like a number, and an array position would be json[123] with no quotes. The empty key is json[""], and a quote inside a key is escaped with a backslash, as in JSON.
Accented and non-Latin keys such as naïve and 日本語 are always bracketed. gron 0.7.1 prints those two bare (json.naïve), a spelling that gronify unflatten rejects with invalid character in path.
Sample, sort, save, and indent the output
Sample a big document with --limit
--limit <n> prints the first n lines and then stops reading the input, which is enough to see the shape of a file too large to scroll through.
gronify flatten --limit 5 config.jsonjson = {}json.name = "api"json.port = 8080json.debug = falsejson.owner = nullStopped after 5 lines (--limit); there may be moreThe last line is a notice on stderr, so a pipe or a redirect receives only the five lines. The exit status is 0.
Get a stable key order with --sort
By default, keys print in the order the document has them. --sort sorts the keys of every object at every depth and leaves arrays in their original order:
echo '{"b":1,"a":{"d":4,"c":3},"10":0,"2":0}' | gronify flatten --sortjson = {}json["10"] = 0json["2"] = 0json.a = {}json.a.c = 3json.a.d = 4json.b = 1Keys compare by UTF-16 code unit, which puts "10" before "2". Two documents that differ only in key order give identical sorted output, so the system diff reports only real changes, as the guide to comparing two JSON files shows.
Write to a file with -o
-o <file> (long form --output) writes the lines to a file and confirms on stderr. A shell redirect with > gives the same file.
gronify flatten config.json -o config.gronOutput written to config.gronhead -2 config.gronjson = {}json.name = "api"What --pretty does to flattened lines
--pretty indents each line and adds blank lines. Each line is indented two spaces for every dot and opening bracket in its path beyond the first, up to twelve spaces, so lines at the same depth line up. Gronify 1.3.1 and earlier also count the dots and brackets in the value: there lag = 0.5 sits one step deeper than host = "r1", and a = [] line one step deeper than a = {} line. Gronify 1.3.2 counts the path only, and the transcript below comes from that build. A blank line goes before each new top-level key, and also between a top-level = {} or = [] line and its own children:
gronify --pretty flatten config.json | grep replicas json.db.replicas = [] json.db.replicas[0] = {} json.db.replicas[0].host = "r1" json.db.replicas[0].lag = 0.5 json.db.replicas[1] = {} json.db.replicas[1].host = "r2" json.db.replicas[1].lag = 1.25Indented lines still unflatten, but a pattern anchored at ^json matches only 10 of this file's 26 lines once they are indented (7 in 1.3.1). Leave --pretty off when another program reads the output.
Turn flattened lines back into JSON
gronify unflatten reads the lines and writes JSON. Piping one command into the other returns the document unchanged. For this file the result is byte-identical to config.json:
gronify flatten config.json | gronify unflatten{"name":"api","port":8080,"debug":false,"owner":null,"tags":["web","eu"],"db":{"host":"db.internal","replicas":[{"host":"r1","lag":0.5},{"host":"r2","lag":1.25}]},"grid":[[1,2],[3,4]],"limits":{},"plugins":[]}unflatten also fills in missing parent containers automatically, so piping a filtered subset such as gronify search config.json replicas | gronify unflatten rebuilds valid JSON without keeping json = {} or json.db = {}. The guide to unflattening gron lines back into JSON covers filtered input, line order, and indented output.
Flatten JSON with jq: lines or one flat object
Flattening JSON can mean two different results. One is the form on this page: one line per value, in the style of gron, for grep, diff, and reading. The other is still JSON: a single one-level object whose keys are dotted paths. Gronify writes only the first.
jq can print the line form with a one-liner that is often quoted:
jq -r 'paths(scalars) as $p | "\($p|join(".")) = \(getpath($p))"' config.jsonname = apiport = 8080tags.0 = webtags.1 = eudb.host = db.internaldb.replicas.0.host = r1db.replicas.0.lag = 0.5db.replicas.1.host = r2db.replicas.1.lag = 1.25grid.0.0 = 1grid.0.1 = 2grid.1.0 = 3grid.1.1 = 4On jq 1.8.2 that is 13 lines where gronify flatten printed 26. The container lines are gone, which hides the empty limits and plugins. debug and owner are missing too, because paths(scalars) skips false and null. Writing paths(scalars | true) keeps them, and ending with getpath($p) | tojson keeps the quotes on strings. Array positions and keys look alike (tags.0).
For the flat-object form, collect the same paths into one object:
jq -c '[paths(scalars | true) as $p | {key: ($p | join(".")), value: getpath($p)}] | from_entries' config.json{"name":"api","port":8080,"debug":false,"owner":null,"tags.0":"web","tags.1":"eu","db.host":"db.internal","db.replicas.0.host":"r1","db.replicas.0.lag":0.5,"db.replicas.1.host":"r2","db.replicas.1.lag":1.25,"grid.0.0":1,"grid.0.1":2,"grid.1.0":3,"grid.1.1":4}The npm package flat builds the same object without a jq program: npx flat config.json (flat 6.0.1) printed these keys plus "limits": {} and "plugins": []. Dotted keys cannot tell a dot inside a key from a level of nesting, so two paths can collide and one value is lost. The line form keeps both:
cat dots.json{"a.b":1,"a":{"b":2}}jq -c '[paths(scalars | true) as $p | {key: ($p | join(".")), value: getpath($p)}] | from_entries' dots.json{"a.b":2}gronify flatten dots.jsonjson = {}json["a.b"] = 1json.a = {}json.a.b = 2If you need a flat object to load into a spreadsheet or a key-value store, jq or flat is the better tool, because Gronify has no flat-object output. For the line form, how to grep JSON covers searching it, and finding the path to a key covers locating one value.
| Job | Form | Tool |
|---|---|---|
| Search, read, or compare a document whose shape you do not know | One line per value | gronify flatten, gron, or fastgron |
| Load the values into a spreadsheet or a key-value store | Flat object | jq or flat |
| Flatten a JSON Lines log with one object per line | One line per value | gronify flatten -s, gron -s, or fastgron -s |