How to extract a paticular key from the json

Advertisements

I am trying to extract values from a json that I obtained using the curl command for api testing. My json looks as below. I need some help extracting the value "20456" from here?

 {
  "meta": {
    "status": "OK",
    "timestamp": "2022-09-16T14:45:55.076+0000"
  },
  "links": {},
  "data": {
    "id": 24843,
    "username": "abcd",
    "firstName": "abc",
    "lastName": "xyz",
    "email": "abc@abc.com",
    "phone": "",
    "title": "",
    "location": "",
    "licenseType": "FLOATING",
    "active": true,
    "uid": "u24843",
    "type": "users"
  }
}
{
  "meta": {
    "status": "OK",
    "timestamp": "2022-09-16T14:45:55.282+0000",
    "pageInfo": {
      "startIndex": 0,
      "resultCount": 1,
      "totalResults": 1
    }
  },
  "links": {
    "data.createdBy": {
      "type": "users",
      "href": "https://abc@abc.com/rest/v1/users/{data.createdBy}"
    },
    "data.fields.user1": {
      "type": "users",
      "href": "https://abc@abc.com/rest/v1/users/{data.fields.user1}"
    },
    "data.modifiedBy": {
      "type": "users",
      "href": "https://abc@abc.com/rest/v1/users/{data.modifiedBy}"
    },
    "data.fields.projectManager": {
      "type": "users",
      "href": "https://abc@abc.com/rest/v1/users/{data.fields.projectManager}"
    },
    "data.parent": {
      "type": "projects",
      "href": "https://abc@abc.com/rest/v1/projects/{data.parent}"
    }
  },
  "data": [
    {
      "id": 20456,
      "projectKey": "Stratus",
      "parent": 20303,
      "isFolder": false,
      "createdDate": "2018-03-12T23:46:59.000+0000",
      "modifiedDate": "2020-04-28T22:14:35.000+0000",
      "createdBy": 18994,
      "modifiedBy": 18865,
      "fields": {
        "projectManager": 18373,
        "user1": 18628,
        "projectKey": "Stratus",
        "text1": "",
        "name": "Stratus",
        "description": "",
        "date2": "2019-03-12",
        "date1": "2018-03-12"
      },
      "type": "projects"
    }
  ]
}

I have tried the following, but end up getting error:

▶ cat jqTrial.txt | jq '.data[].id'
jq: error (at <stdin>:21): Cannot index number with string "id"
20456

Also tried this but I get strings outside the object that I am not sure how to remove:

cat jqTrial.txt | jq '.data[]'

>Solution :

Assuming you want the project id not the user id:

jq '
    .data
    | if type == "object" then . else .[] end
    | select(.type == "projects")
    | .id
' file.json

There’s probably a better way to write the 2nd expression

Leave a ReplyCancel reply