I have two JSON files with the following content:
foo.json:
{
"name": "foo",
"block": {
"one": 1,
"two": "2"
},
"otherData": {
"two": 1,
"one": "2"
}
}
bar.json:
{
"name": "bar"
}
I want to copy the block from foo.json to bar.json in one line so bar.json looks like this:
{
"name": "bar",
"block": {
"one": 1,
"two": "2"
}
}
I tried:
jq --argjson block '{"block": "$(jq '.block' ./foo.json)"}' '. = [$block]' ./bar.json | sponge ./bar.json
CodePudding user response:
The
operator can be used to combine multiple objects together. Having the object enclosed with {}
selects the whole object for inclusion.
jq ' . ( input | {block} )' bar.json foo.json | sponge bar.json
Note: sponge
is a utility from the moreutils
package, which needs to be installed separately on your system. See setup instructions on the moreutils page
Exercise caution while using the tool, because it overwrites whatever content that is coming in from the standard input to the target file specified. If not completely sure, verify the result by writing to standard output before running sponge.