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?

myrdd
  • 3,222
  • 2
  • 22
  • 22
jagwar3
  • 95
  • 1
  • 6

2 Answers2

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.

myrdd
  • 3,222
  • 2
  • 22
  • 22
-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}

Sailendra Pinupolu
  • 1,038
  • 1
  • 10
  • 8
  • 2
    Please consider adding some wording to explain what you have done with the code. – Charles C. Apr 20 '16 at 21:40
  • Sure, added more details. – Sailendra Pinupolu Apr 21 '16 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 '16 at 03:05