3

Suppose I have the json:

[
 [0, "a"],
 [1, "b"],
 [2, "c"]
]

How can I create a JMESPath projection to get:

[
  {"id": 0, "name": "a"},
  {"id": 1, "name": "b"},
  {"id": 2, "name": "c"}
]
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
jack
  • 147
  • 1
  • 7

2 Answers2

1

For a pure JMESPath solution — not relaying on any programming language nor on any templating language — use the query:

[*].{id: @[0], name: @[1]}

The @ sign represents the current node, so, in your case, one of the list of list that JMESPath is currently considering.

This would yield your expected output:

[
  {
    "id": 0,
    "name": "a"
  },
  {
    "id": 1,
    "name": "b"
  },
  {
    "id": 2,
    "name": "c"
  }
]

Also, because the current node is implicit in a projection, you can even shorten it to

[*].{id: [0], name: [1]}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
0

If you want to transform your data to list of dict with JMESPath:

result = jmespath.search('[*] | [{"id":[0][0], "name":[0][1]},{"id":[1][0], "name":[1][1]},{"id":[2][0], "name":[2][1]}]', data)

I see you have tagged jinja2, so its easy to build an automatic and generic template search for JMESPath

search = Template('[*] | ['
         '{% for l1 in range(data|length) %}'                
         '{ "id": [{{ loop.index0 }}][0], "name": [{{ loop.index0 }}][1] }'
         '{% if not loop.last %},{% else %}]{% endif %}'                  
         '{% endfor %}').render(data=data)

result = jmespath.search(search, data)

Result:

[{'id': 0, 'name': 'a'}, {'id': 1, 'name': 'b'}, {'id': 2, 'name': 'c'}]
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Frenchy
  • 16,386
  • 3
  • 16
  • 39