How to combine two arrays (`keys` and `values`) into an object using JMESPath?

喜欢而已 提交于 2021-02-16 16:00:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!