0

Given this input

{
  "data": [
    {
      "id": "001",
      "metadata": {
        "item1": 1
      },
      "records": [
        {
          "name": "name1",
          "type": "type1"
        },
        {
          "name": "name2",
          "type": "type2"
        }
      ]
    },
    {
      "id": "002",
      "metadata": {
        "item1": 1
      },
      "records": [
        {
          "name": "name1",
          "type": "type1"
        }
      ]
    },
    {
      "id": "003",
      "metadata": {},   
      "records": [
        {
          "name": "name1",
          "type": "type1"
        },
        {
          "name": "name2",
          "type": "type2"
        }
      ]
    }
  ]
}

I am trying to output this

[
  {
    "id": "001",
    "Item1": 1,
    "Name": "name2"
  },
  {
    "id": "002",
    "Item1": 1,
    "Name": null
  },
  {
    "id": "003",
    "Item1": null,
    "Name": "name2"
  }
]

However using this

jq '[.data[] | {id, "Item1": .metadata.item1, "Name": .records[] | select(.type == "type2").name}]'

jq query I am getting this

[
  {
    "id": "001",
    "Item1": 1,
    "Name": "name2"
  },
  {
    "id": "003",
    "Item1": null,
    "Name": "name2"
  }
]

How can I get the '002' id object to output as well? I have tried various if then else conditions statements but to no avail.

2 Answers 2

1

I am quite new to jq so this is probably not an optimal solution.

If you map the select onto the records array instead, the surrounding object is not removed. For example:

parse.jq

[
  .data[] | 
  {
    id    : .id,
    Item1 : .metadata.item1,
    Name  : .records | map(select(.type == "type2"))[0].name
  }
]

Run it like this:

jq -f parse.jq file.json

Output:

[
  {
    "id": "001",
    "Item1": 1,
    "Name": "type2"
  },
  {
    "id": "002",
    "Item1": 1,
    "Name": null
  },
  {
    "id": "003",
    "Item1": null,
    "Name": "type2"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

0

It can be because the 2nd nested array doesn't satisfy the condition

select(.type == "type2")

1 Comment

I understand this but how can I have something that doesn't satisfy this condition yet still return something from the parent object metadata.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.