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

2

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?

Dualistic answered 9/8, 2015 at 3:23 Comment(0)
V
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.

Villasenor answered 25/8, 2018 at 11:21 Comment(0)
A
-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}

Apograph answered 20/4, 2016 at 21:30 Comment(3)
Please consider adding some wording to explain what you have done with the code.Sergio
Sure, added more details.Apograph
@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.Dualistic

© 2022 - 2024 — McMap. All rights reserved.