Home > Net >  How to solve JQ processing as multiple dictionaries if document has an array?
How to solve JQ processing as multiple dictionaries if document has an array?

Time:12-26

I have the following JSON document

[
  {
    "description": "Component 1",
    "tags": [
      "abc",
      "123",
      "xyz"
    ]
  },
  {
    "description": "Component 2",
    "tags": [
      "def",
      "foo",
      "bar"
    ]
  },
  {
    "description": "Component 3",
    "tags": [
      "def"
    ]
  }
]

I have written below JQ filter to parse the JSON, the expected output is not to generate multiple dictionaries.

{ (.[].description):(.[].tags)}

After applying the filter, i get the below output with multiple dictionaries because of the tags array

{
  "Component 1": [
    "abc",
    "123",
    "xyz"
  ]
}
{
  "Component 1": [
    "def",
    "foo",
    "bar"
  ]
}
{
  "Component 1": [
    "def"
  ]
}
{
  "Component 2": [
    "abc",
    "123",
    "xyz"
  ]
}
{
  "Component 2": [
    "def",
    "foo",
    "bar"
  ]
}
{
  "Component 2": [
    "def"
  ]
}
{
  "Component 3": [
    "abc",
    "123",
    "xyz"
  ]
}
{
  "Component 3": [
    "def",
    "foo",
    "bar"
  ]
}
{
  "Component 3": [
    "def"
  ]
}


The output I am expecting is without multiple dictionaries as below

{
  "Component 1": [
    "abc",
    "123",
    "xyz"
  ]
}
{
  "Component 2": [
    "def",
    "foo",
    "bar"
  ]
}
{
  "Component 3": [
    "def"
  ]
}

How can I generate the above-expected output using JQ?

CodePudding user response:

You can convert to this one

jq '.[] | { (.description) : .tags }'

in order to get rid of multiple occurences

Demo

  • Related