Shailendra Sadh
Shailendra Sadh

Reputation: 71

Not able to Iterate through JSON response object with JQ in Unix shell

I am trying to iterate through a JSON object in UNIX, where the idea is to pickup different values and append it to a string and forward it as a syslog. Below is the code.

//picking up the length of Object
count=$(jq '.content | length' red)
#echo $count

    enter code here

for((i=0;i<$count;i++))
do
        echo "MY VALUE OF I"
        echo $i
        //THE BELOW LINE GIVES ERROR UPON USAGE of $i
        id="$(cat red | jq '.content[$i].id')"
        source=$(cat red | jq '.content[$i].entitySummary.source')
        .
        .

        #syslogString="ID=$id SOURCE=$source SUMMARY=$summaryText TITLE=$title DESCRIPTION=$description SEVERITY=$severity MITIGATION=$mitigation IMPACT=$impactDescrip$

        echo $id
        echo "value of ID ($id)"

I am receiving compilation error with content[$i] and cant get a workaround the same.

The response class looks like this:

Page {
    content ( array[ ClientIncident ] )
        The list of results that make up the page. The number of elements should be less than or equal to the currentPage size.
    currentPage ( Pagination )
        Size and offset information about the current page.
    total ( integer )
        The total number of results found. If there are a large number of results, this may be an estimate. Accuracy should improve as the page approaches the end of the resultset.
} 

under content the JSON response looks as below:

{
  "content": [
    {
      "id": 951653,
      "version": 12,
      "score": 100,
      "entitySummary": {
        "source": "somewebsite",
        "summaryText": "someTEXT here",
        "domain": "www.domian.com",
        "sourceDate": "2014-12-19T17:00:00.000Z",
        "type": "WEB_PAGE"
      },
      "type": "SomeTYPE",
      "title": "some Title",
      "description": "some description ",
      "occurred": "2014-12-19T17:00:00.000Z",
      "verified": "2014-12-19T17:17:22.326Z",
      "tags": [
        {
          "id": 424,
          "name": "Data Breach or Compromise",
          "type": "IMPACT_EFFECTS"
        },
        {
          "id": 1064,
          "name": "United States",
          "type": "TARGET_GEOGRAPHY"
        },
       ],
      "severity": "MEDIUM",
      "clientId": "NET",
      "alerted": "2014-12-19T17:39:55.500Z",
      "mitigation": "MititgationINFO",
      "impactDescription": "IMpact description": 0
    },
    {
      "id": 951174,
      "version": 8,
      "score": 100,
      "entitySummary": {

Upvotes: 3

Views: 1937

Answers (1)

Shailendra Sadh
Shailendra Sadh

Reputation: 71

Ok I got the answer for this.

We can use the below syntax to make is work in the for loop.

id=$(cat red | jq '.content['${i}'].id')

Upvotes: 4

Related Questions