gron icon indicating copy to clipboard operation
gron copied to clipboard

Root object other than "json"

Open bowman opened this issue 5 years ago • 3 comments

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 -u

Thank you

bowman avatar Nov 07 '19 09:11 bowman

Hello, nice feature.

I'd rename the option name to --root with json as default value and accompany it with --noroot to remove the whole json. from the output.

I just run into a use case where I'd like to copy the path from gron output and use it as a jq path after .

Something like this:

$ gron package.json | grep gulp:build
json.scripts["gulp:build"] = "gulp build";
$ jq '.scripts["gulp:build"]' < package.json
"gulp build"

So it would be very helpful to have it like this:

$ gron --noroot package.json | grep gulp:build
scripts["gulp:build"] = "gulp build";
$ jq '.scripts["gulp:build"]' < package.json
"gulp build"

aleksandr-vin avatar Mar 13 '20 09:03 aleksandr-vin

I just came here to ask for something like @aleksandr-vin suggested. I love using gron to find the structure pattern I need to feed to jq in a script to extract the data I'm looking for, and the fact that jq and gron have a different root object is an annoying impedance mismatch. I can hack something like

gronq() { gron $@ |sed 's/^json//' }

for that, but it forces output to monochrome and probably has other problems.

scentoni avatar Feb 22 '23 17:02 scentoni

I implemented --root in https://github.com/adamritter/fastgron

adamritter avatar Jul 06 '23 08:07 adamritter