问题
I have a JSON object with two arrays — one keys
array and one values
array, both of the same length. Using jmespath, I want to construct a new object using the values of the keys
array as the keys and the values of the values
array as the values, like array_combine in PHP.
For example, here's the input:
{
"keys": [
"a",
"b",
"c"
],
"values": [
1,
2,
3
]
}
And here is the output I'm expecting:
{
"a": 1,
"b": 2,
"c": 3
}
Is there any built-in function to achieve this?
回答1:
Unfortunately, it looks like this is not possible yet.
Github issue: jmespath.py#152 — (located in the repo of the Python implementation)
You would need the zip
and from_items
functions, proposed (!) for the specs in this github pull request.
回答2:
jmespath is popular library to parse/query JSON files. More examples at http://jmespath.org/tutorial.html
In below code
- js is the provided json content
- jp.search('keys',json.loads(js)) produces the list : [u'a', u'b', u'c']
- jp.search('values',json.loads(js)) produces the list : [1, 2, 3]
zip combines the two lists and dict() converts the tuples to a dictionary
import json import jmespath js = '''{ "keys": [ "a", "b", "c" ], "values": [ 1, 2, 3 ] }''' print (dict(zip(jp.search('keys',json.loads(js)),jp.search('values',json.loads(js)))))
output: {u'a': 1, u'c': 3, u'b': 2}
来源:https://stackoverflow.com/questions/31900580/how-to-combine-two-arrays-keys-and-values-into-an-object-using-jmespath