Search code examples
bashwhile-loopjqifs

jq: parse and display multiple values in JSON


I have this test.json file

{
  "list": [
    {
      "expand": "xx",
      "id": "xxxxx",
      "self": "https",
      "key": "test-11",
      "fields": {
        "field_1": "1234"
      }
    },
    {
      "expand": "xx",
      "id": "xxxxx",
      "self": "https",
      "key": "test-10",
      "fields": {
        "field_1": "1235",
        "field_2": null
      }
    }
  ]
}

I am trying to read the values using IFS while loops:

cat test.json| jq -r '[.list[]| ([.key]|tostring) + "," + "\(.fields| .field_1)"]|@tsv' \
| while IFS="," read -r key field_1; do
echo "$key $field_1"
curl -s https ://thisistest.com/api/$key/$field_1
done;
echo output displays only: test-11

I would like to get the values of key and field_1 to use them in the curl request.


Solution

  • The jq command from @Kev in comment will extract the values you want, each pair per line, like this:

    > jq -r '.list[]|[.key,.fields.field_1]|@tsv' test.json
    test-11 1234
    test-10 1235
    

    Here is how you can modify your script to make your curl requests per value pair.

    #!/bin/bash
    while read -r key field_1; do
        echo curl -s https://thisistest.com/api/$key/$field_1
    done < <( jq -r '.list[]|[.key,.fields.field_1]|@tsv' test.json )
    

    Remove echo if you are ok with your testing.