Tuesday, October 25, 2022

[SOLVED] edit a json file using ouput of another multi line file

Issue

I have a json file and i need to edit it using value from some other file. The file whose value needs to be applied to the json file is a multi string file

Here i am using a jenkins groovy shell to output the contents of a file xyz.txt to a variable called file that can be used to edit the json file.

sh '''file=`cat xyz.txt`
      printf '{ "body": "" }' > myfile.json
      sed ...................
'''

Now using the above i have a json file like the below

{ "body": "" }

But i would like to replace the empty quotes "" next to "body" with the value from the output of xyz.txt which means the value of ${file} and is hence a multi string with separate lines.

How do I do that, probably using sed or something else?


Solution

Given -R/--raw-input and -s/--slurp flags together, jq makes input file's content accessible through . filter. This can be used for your purpose like this:

jq -Rs '{body:.}' xyz.txt > myfile.json


Answered By - oguz ismail
Answer Checked By - Candace Johnson (WPSolving Volunteer)