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"}
]
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]}
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'}]