anuribs anuribs - 3 months ago 12
JSON Question

Extract specific field from json output using jq

I have a json output as follows:

{
"example": {
"sub-example": [
{
"name": "123-345"
"tag" : 100,
},
{
"name": "234-456"
"tag" : 100,
},
{
"name": "4a7-a07a5"
"tag" : 100,
}
]
}
}


I want to extract the values of the three "name" fields and store it in three variables. I had tied to do
cat test | jq '.["example.sub-example.name"]'
(where test is the file containing this json output) to extract the values of the "name" field but that doesn't work. Can anyone tell me how to achieve this using jq (or some other method)? Thanks in advance.

Answer

If you just want to extract the name fields, the command you're looking for is jq '.example."sub-example" | .[] | .name'. If you want to keep the names in an array, wrap the whole jq expression in square brackets.

I warn you, though, that your sample JSON has a syntax error. If you're using that one to test, it won't work; use this here:

{
  "example": {
    "sub-example": [
      {
        "name": "123-345",
        "tag" : 100
      },
      {
        "name": "234-456",
        "tag" : 100
      },
      {
        "name": "4a7-a07a5",
        "tag" : 100
      }
    ]
  }
}
Comments