Home > OS >  How do I get wanted data structure with jq
How do I get wanted data structure with jq

Time:09-03

I have lots of data from where I try to extract details when value contains certain string (here "whatamImissing").

[
 {
  "http_method": "GET",
  "revision": "2226.1.0.17580034458892190058.1564516060",
  "results": [
    {
      "origin": 80,
      "name": "foo",     
      "comments": "whatamImissing",
      "emptydata": ""
    }
  ],
  "bar": "thisIsneeded",
  "meta": "metainfo"
 }
]

so far the nearest I've managed is with this:

jq '.[] | [.bar, (.results[] | select(.comments | test("whatamImissing"))|{name: .name, comments: .comments})]'

which returns

[
  "thisIsneeded",
  {
    "name": "foo",
    "comments": "whatamImissing"
  }
]

What I want is

{
  "bar": "thisIsneeded",
  {
    "name": "foo",
    "comments": "whatamImissing"
  }
}

CodePudding user response:

Another take:

jq '
    map({
        bar,
        result: (
            .results[]
            | select(.comments | contains("whatamI"))
            | {name, comments}
        )
    })
'
[
  {
    "bar": "thisIsneeded",
    "result": {
      "name": "foo",
      "comments": "whatamImissing"
    }
  }
]

CodePudding user response:

Here's one way with a valid output JSON as array of objects:

jq 'map(
  .results[] as $r | select($r.comments | test("whatamImissing"))
  | {bar}   ($r | {name, comments})
)'
[
  {
    "bar": "thisIsneeded",
    "name": "foo",
    "comments": "whatamImissing"
  }
]

Demo


Here's another way with a nested array

jq 'map(
  .results |= map(select(.comments | test("whatamImissing"))
  | {name, comments}) | {bar, results}
)'
[
  {
    "bar": "thisIsneeded",
    "results": [
      {
        "name": "foo",
        "comments": "whatamImissing"
      }
    ]
  }
]

Demo

  • Related