9

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?

2 Answers 2

4

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.

-1

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}

3
  • 2
    Please consider adding some wording to explain what you have done with the code.
    – Charles C.
    Apr 20, 2016 at 21:40
  • Sure, added more details. Apr 21, 2016 at 16:28
  • 3
    @Sai, I appreciate the effort, but I was looking for a solution that used jmespath only and your solution uses Python to zip the two arrays. The reason for wanting a jmespath-only approach is I want to build an API where users provide a jmespath script to reshape a JSON response to their liking without compromising the server by executing arbitrary Python code.
    – jagwar3
    Apr 22, 2016 at 3:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.