Home > front end >  Inserting a long HTML file to a Json file using JQ
Inserting a long HTML file to a Json file using JQ

Time:02-16

I'm trying to insert the content of a long html file to my json file using the command I found on this Insert an HTML file into a JSON file value using JQ

I'm using this command because the other ones are meant for short argument only, whereas in my usecase, the html content can be quite long.

jq --slurpfile texts <(jq -Rs file.html) '.body=$texts[0]' file.json >newfile.json

however, I'm getting this error

jq: error: file/0 is not defined at <top-level>, line 1:
file.html
jq: 1 compile error

the content of the html file doesn't seem to matter. I tried using only a simple html file like this

<html>
  <body></body>
</html>

And still got the same error.

btw before I do the jq command I'm using sed 's/&/\&amp;/g; s/"/\\\"/g; s/'"'"'/\\\'"'"'/g' to make the html file an encoded string as described in the same question I linked as well

What exactly am I doing wrong? the error message doesn't really say anything other than that, so I'm clueless as to what went wrong

I appreciate any help

CodePudding user response:

You're missing a filter in the inner jq call. Insert the identity filter . as in jq -Rs . file.html:

jq --slurpfile texts <(jq -Rs . file.html) '.body=$texts[0]' file.json >newfile.json

Additional notes:

You could also use --argfile instead of --slurpfile which gives you the string itself rather than an array, from which you wouldn't have to extract the first element .[0] anymore:

jq --argfile texts <(jq -Rs . file.html) '.body=$texts' file.json >newfile.json

Also, if you are using jq 1.6, there's yet an easier way to do it. Use --rawfile instead of --argfile or --slurpfile and you don't need the other jq at all anymore:

jq --rawfile texts file.html '.body=$texts' file.json >newfile.json
  • Related