How to combine two arrays into keys and values ​​using Jmespath

I have a JSON object with two arrays. Using jmespath, I want to build a new object using one array as keys and another as values. Similar to array_combine in PHP.

For example, here is the input:

 { "keys": [ "a", "b", "c" ], "values": [ 1, 2, 3 ] } 

And here is the result that I expect:

 { "a": 1, "b": 2, "c": 3 } 

Is there a built-in function to achieve this?

+4
source share
1 answer

jmespath is a popular library for parsing / querying JSON files. Additional examples at http://jmespath.org/tutorial.html

In the code below

  • js is the json content provided
  • jp.search ('keys', json.loads (js)) creates a list: [u'a', u'b ', u'c']
  • jp.search ('values', json.loads (js)) creates a list: [1, 2, 3]
  • zip concatenates the two lists, and dict () converts the tuples into 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}

-2
source

All Articles