0

I want to move a JS object from one file to another. I am currently trying to use jq to do this, but I'm having issues getting it to output the result to a file using pretty printing. In case you were wondering, I am trying to move duplicate swagger definitions into a common file.

This is my script:

content=`jq '.definitions.foo' ./src.swagger.json`
src_without_content=`jq 'del(.definitions.foo)' ./src.swagger.json`
echo $src_without_content > ./src.swagger.json
dest_with_content=`jq --argjson content "$content" '.definitions |= .+ { "foo": $content }' ./dest.swagger.json`
echo $dest_with_content > ./dest.swagger.json

Basically, I am trying to capture the object that I want, then remove it from the source file, then add it to the destination. I modify both files by creating the data that I want in the files, then overwriting them.

When I tried using the output to directly write to a file (instead of first storing it in environment variables), the file was overwritten with a blank file:

jq 'del(.definitions.foo)' ./src.swagger.json > ./src.swagger.json

With my current script, the content is valid and as expected, but it isn't formatted nicely. Instead, it is being printed as one solid line. I read into this, and by default jq is supposed to use pretty printing. Perhaps it is getting lost when I store the result in an environment variable? I've seen a few posts, but none of them seem to discuss how to write the output to a file.

Am I missing something? Is there a way to do this? Any help is appreciated. Thanks!

In case it matters, I am running this script on a mac.

peak
  • 105,803
  • 17
  • 152
  • 177
A. Davidson
  • 397
  • 1
  • 4
  • 14

1 Answers1

0

Am I missing something?

Yes - you cannot reliably use shell redirection to read and write the same file in the way you are expecting. That's just the way things are :-(

Is there a way to do this?

Yes. One way is to use sponge. (On a Mac, you could install it using brew install moreutils.) Another is to use https://github.com/nicowilliams/inplace

For further details and options, see https://github.com/stedolan/jq/wiki/FAQ (search for sponge).

peak
  • 105,803
  • 17
  • 152
  • 177