0

This seems like a super simple task but I somehow can't figure it out / find an answer online.

I have some piped output in the form of {"key": "value"} and I need to insert it into an existing json file along the lines of:

{
 "existing_key":"value"
}

to get:

{
 "existing_key":"value",
 "key": "value"
}

How do I do this using jq?

ilmoi
  • 1,994
  • 2
  • 21
  • 45
  • There are quite a lot of "how do I merge two JSON files with jq?" already in our knowledge base, though granted many are more complex than this case -- it did take some looking to find one that was a perfect fit. – Charles Duffy Jan 20 '21 at 18:32
  • @CharlesDuffy: You are right, but I was tempted to not close it as it was specifically saying coming from a piped output – Inian Jan 20 '21 at 18:35
  • 1
    @Inian, ...added https://stackoverflow.com/questions/53533697/jq-with-multiple-inputs-from-different-sources as a second duplicate to cover that aspect of the question. – Charles Duffy Jan 20 '21 at 18:37
  • 1
    `echo '{...}' | jq -s add - tmp.json`. – chepner Jan 20 '21 at 18:40
  • This works 90%, but doesn't completely do it. It outputs the correctly merged json to stdout, but when I try to write it to the same file I read from, I get no change. Command: `echo '{...}' | jq -s add - tmp.json > tmp.json`. Is there no way other than creating a temp file? – ilmoi Jan 20 '21 at 18:55
  • @ilmoi, that's another duplicate, this time of https://stackoverflow.com/questions/6696842/how-can-i-use-a-file-in-a-command-and-redirect-output-to-the-same-file-without-t – Charles Duffy Jan 20 '21 at 19:41
  • @ilmoi, ...see in particular https://stackoverflow.com/a/55655338/14122 (with the bugfix I just added as a suggestion in comments; if it didn't have that bug I'd have upvoted it so it wouldn't be at 0). – Charles Duffy Jan 20 '21 at 19:43

0 Answers0