Eldar88 Eldar88 - 2 years ago 75
Python Question

Create named variables in the local scope from JSON keys

Is there a way I can create named variables in the local scope from a json file?

document json

This is my json file, I would like to create variables in the local scope named as the path of my json dictionary

This is how I manually create them, I would like to do it automatically for all the json file. Is it possible?

class board(object):
def __init__(self, json, image):
self.json = json
self.image = image

def extract_json(self, *args):
with open(self.json) as data_file:
data = json.load(data_file)
jsonpath_expr = parse(".".join(args))
return jsonpath_expr.find(data)[0].value

MyAgonism = board('document.json', './tabellone.jpg')

boxes_time_minutes_coord = MyAgonism.extract_json("boxes", "time_minutes", "coord")
boxes_time_seconds_coord = MyAgonism.extract_json("boxes", "time_seconds", "coord")
boxes_score_home_coord = MyAgonism.extract_json("boxes", "score_home", "coord")

Answer Source

I think you're making this much more complicated than it needs to be.

with open('document.json') as f:
    d = json.load(f)

time_minutes_coords = d['boxes']['time_minutes']['coord']
time_seconds_coords = d['boxes']['time_seconds']['coord']
score_home_coords = d['boxes']['score_home']['coord']

If you actually want to create named variables in the local scope from the keys in your json file, you can use the locals() dictionary (but this is a terrible idea, it's far better just to reference them from the json dictionary).

# Flatten the dictionary keys.
# This turns ['boxes']['time_minutes']['coord'] 
# into "boxes_time_minutes_coord"
def flatten_dict(d, k_pre=None, delim='_', fd=None):
    if fd is None:
        fd = {}
    for k, v in d.iteritems():
        if k_pre is not None:
            k = '{0}{1}{2}'.format(k_pre, delim, k)
        if isinstance(v, dict):
            flatten_dict(v, k, delim, fd)
            fd[k] = v
    return fd

fd = flatten_dict(d)

print boxes_time_minutes_coord

Lots of caveats, like the possibility of overwriting some other variable in your local scope, or the possibility that two dictionary keys could be identical after flattening unless you choose a delimiter that doesn't appear in any of the dictionary keys. Or that this won't work if your keys contain invalid characters for variable names (like spaces for example).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download