how to update each object in a json array using jq

ghz 8months ago ⋅ 64 views

I have an array of objects that looks like this:

[
    {"host": "1.exampl.com", "path": "/dir1/file.html"},
    {"host": "2.exampl.com", "path": "/dir2/file.html"},
    {"host": "3.exampl.com", "path": "/dir3/file.html"}
]

and I want to add a new key in each of those objects, which will create the URL using the host and path, so I would look like this:

[
    {"host": "1.exampl.com", "path": "/dir1/file.html", "url": "http://1.example.com/dir1/file.html"},
    {"host": "2.exampl.com", "path": "/dir2/file.html", "url": "http://2.example.com/dir2/file.html"},
    {"host": "3.exampl.com", "path": "/dir3/file.html", "url": "http://3.example.com/dir3/file.html"}
]

how can I do that using jq.

I tried doing ".[] |= . { . + {\"url\": \"http://\" + .host + .path } }" but this didn't work and it returned this error: jq: error: syntax error, unexpected '}', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:

Answers

You were close with your attempt. Here's the correct way to achieve this using jq:

jq '.[] |= . + { "url": "http://\(.host)\(.path)" }' input.json

This command will iterate over each object in the array (.[].) and for each object, it will add a new key called "url" with the concatenated value of "http://" followed by the "host" and "path" values from the object.

For example:

Input JSON (input.json):

[
    {"host": "1.exampl.com", "path": "/dir1/file.html"},
    {"host": "2.exampl.com", "path": "/dir2/file.html"},
    {"host": "3.exampl.com", "path": "/dir3/file.html"}
]

Command:

jq '.[] |= . + { "url": "http://\(.host)\(.path)" }' input.json

Output:

[
  {
    "host": "1.exampl.com",
    "path": "/dir1/file.html",
    "url": "http://1.exampl.com/dir1/file.html"
  },
  {
    "host": "2.exampl.com",
    "path": "/dir2/file.html",
    "url": "http://2.exampl.com/dir2/file.html"
  },
  {
    "host": "3.exampl.com",
    "path": "/dir3/file.html",
    "url": "http://3.exampl.com/dir3/file.html"
  }
]

This will produce the desired output with the "url" key added to each object in the array.