Root object other than "json"
Author: bowmanCreated Nov 7, 2019Updated Jul 6, 2023
Hello. I have a minor feature suggestion.
I'd like to have a -v/--var option that sets the name of the root output variable:
echo '[1,2]' | gron -v 'a'
a = [];
a[0] = 1;
a[1] = 2;My use case is replacing a nested leaf with content from another json file, so in this case I'd have a complicated var like 'json[0].key1' and replace the input line with multiple output lines.
(I can imagine just putting a compact single line chunk of json as a value, but that isn't permitted either currently. There may also be other ways to tackle this problem)
Here's a more complicated example:
$ head input.json a.json b.json
==> input.json <==
[ { "key1": "a", "key2": 123}, { "key1": "b", "key2": 345} ]
==> a.json <==
{ "id": "a", "value": [1,2] }
==> b.json <==
{ "id": "b", "value": [3,4] }Here's a pipeline that greps the "key1" lines and replaces them with the content from another file:
$ gron input.json | perl -ple 'if(/^(.*key1) = "(.*?)";$/) { $_ = `gron $2.json | sed "s/^json/$1/"`; chomp }' | gron -u | jq -c
[{"key1":{"id":"a","value":[1,2]},"key2":123},{"key1":{"id":"b","value":[3,4]},"key2":345}]With this suggestion it the sed could be dropped:
gron input.json | perl -ple 'if(/^(.*key1) = "(.*?)";$/) { $_ = `gron -v $1 $2.json`; chomp }' | gron -uThank you
Source: tomnomnom/gron