Search code examples
jsonjmespath

jmespath flatten multiple hash values


Ideally, I want to write a query that returns a flat list output: ["abc", "bcd", "cde", "def"] from the following JSON sample:

{
  "l_l": [
    [1,2,3],
    [4,5,6]
  ],
  "l_h_l": [
    { "n": [10,2,3] },
    { "n": [4,5,60] }
  ],
  "l_h_m": [
    {
      "n": {
        "1234": "abc",
        "2345": "bcd"
      }
    }, {
      "n": {
        "3456": "cde",
        "4567": "def"
      }
    }
  ]
}

The closest I can get is l_h_m[].n.* which returns the contents that I want as an unflattened list of lists:

[
  [
    "abc",
    "bcd"
  ],
  [
    "cde",
    "def"
  ]
]

jmespath lets you flatten lists of lists. Queries l_l[] and l_h_l[].n[] both returned flattened results, when the source json is structured that way.


Solution

  • Looks like your solution just required another flattening operator.

    l_h_m[].n.*[]
    

    returns

    [
      "abc",
      "bcd",
      "cde",
      "def"
    ]