Idan Adar
Idan Adar

Reputation: 44516

jq injects literal newline and escape characters instead of an actual newline

I have the following JSON:

{
  "overview_ui": {
    "display_name": "my display name",
    "long_description": "my long description",
    "description": "my description"
  }
}

I grab it like so:

overview_ui=$(jq -r ".overview_ui" service.json)

I then want to use it to replace content in another JSON file:

jq -r --arg updated_overview_ui_strings "${overview_ui}" '.overview_ui.${language} |= $updated_overview_ui_strings' someOtherFile.json

This works, however it also introduces visible newline \n and escape \ characters instead of actually preserving the newlines as newlines. Why does it do that?

"en": "{\n  \"display_name\": \"my display name\",\n  \"long_description\": \"my long description\",\n  \"description\": \"my description\"\n}",

Upvotes: 0

Views: 1050

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134811

You have read the overview_ui variable in as a string (using --arg) so when you assigned it, you assigned that string (along with the formatting). You would either have to parse it as an object (using fromjson) or just use --argjson instead.

jq -r --argjson updated_overview_ui_strings "${overview_ui}" ...

Though, you don't really need to have to do this in multiple separate invocations, you can read the file in as an argument so you can do it in one call.

$ jq --argfile service service.json --arg language en '
.overview_ui[$language] = $service.overview_ui
' someOtherFile.json

Upvotes: 2

Related Questions