Jitesh Sojitra
Jitesh Sojitra

Reputation: 4043

Getting jq output in single line for JSON output using Bash

I'm calling the TestRail API through a Bash script and getting below output using curl and jq, later I'm parsing it and putting into file. It gives me result fine but keys in different lines, I expect one block should give result in one line. How can I get output in single line using jq and bash?

I tried jq -c and it works but only thorugh CLI, via Bash script file it fails. Not sure what is the wrong when running different way and obviously we need to run through Bash file only.

Code:

jsonOutput=`curl -u $user:$key -X GET -H 'Content-Type: application/json' --insecure --silent $url/index.php?/api/v2/get_results_for_run/$runID | jq -r`

for runDetails in ${jsonOutput}; do
    IFS=","

    if [[ "${runDetails}" = "id" ]] || [[ "${runDetails}" = "status_id" ]]; then
        runDetails=$(echo "${runDetails}" | sed 's/\"//g' | sed 's/{//g' | sed 's/}//g')

        testcaseID=$(echo "${id}")
        testcaseResult=$(echo "${test_id}")
        echo -e "${testcaseID}\t${testcaseResult}" >> ${reportsFile}
    fi
done

Actual:

"id": 425179,
"test_id": 4713650

"id": 425178,
"test_id": 4713649

Expected:

425179, 4713650
425178, 4713649

jq output:

[
  {
    "id": 425179,
    "test_id": 4713650,
    "status_id": 5,
    "created_by": 41,
    "created_on": 1510161282,
    "assignedto_id": null,
    "comment": null,
    "version": null,
    "elapsed": null,
    "defects": null,
    "custom_step_results": [
      {
    "expected": "",
    "actual": "",
    "status_id": 3
      }
    ],
    "custom_severity": null
  },
  {
    "id": 425178,
    "test_id": 4713649,
    "status_id": 1,
    "created_by": 41,
    "created_on": 1510161195,
    "assignedto_id": null,
    "comment": null,
    "version": null,
    "elapsed": "10s",
    "defects": null,
    "custom_step_results": [
      {
    "expected": "",
    "actual": "",
    "status_id": 3
      }
    ],
    "custom_severity": null
  }
]

Upvotes: 1

Views: 1691

Answers (1)

janos
janos

Reputation: 124646

jq can alone parse the JSON to the desired format:

curl ... | jq -r '.[] | (.id | tostring) + ", " + (.test_id | tostring)'

Upvotes: 6

Related Questions