PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How can I copy a JSON block to another file?

 July 23, 2022     bash, jq, json, sponge     No comments   

Issue

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

Solution

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.



Answered By - Inian
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing