1

I have a json-file with n users. I need to replace the id-field with a different UUID for each user. After that, I need to make n curl calls with the json as payload. How can I achieve this?

My json file:

[{
  "id": "a3d920e",
  "name": "Alice",
  "age": 17
},{
  "id": "18db903",
  "name": "Bob",
  "age": 71
},{
  "id": "ff9a32c",
  "name": "Carol",
  "age": 30
}]

I tried this command: jq -c '.[] | objects' mydata.json | jq -c --arg a "$(uuidgen)" '.id = $a'

With that command, I can replace the id field, but I need a unique UUID for each user, whereas the command gives me the identical UUID for all users. And afterwards, I need to run curl -X POST http://localhost:8080 n times with each json-object as payload (with this example file, it would be once for Alice, once for Bob and once for Carol).

I tried to use xargs to achieve this, but could not figure out how to run it together with jq.

1 Answer 1

3

As each object is a single line, you can use read to read the objects in a loop:

jq -c '.[] | objects' mydata.json  | while read obj ; do
    jq -c --arg id "$(uuidgen)" '.id = $id' <<< "$obj" \
    | curl -X POST -d @- http://localhost:8080
done

The -d @- tells curl to read the payload from standard input.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .