Python Forum

Full Version: JSON Parsing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a situation where i need to parse a JSON into relation tables. the JSON comprise of dictionaries, list with 4 -5 level nested. also, have a rules to combine multiple dicts or list into a single relation table. I have kind of started this with recursive logic but trying to see if we have any option to avoid recursive logic but still accomplish same.
same JSON : ( show the context of use case)
Emp : {
K1 : V1
Address : []
K2 : V2
job : {
K3 : v3
}
}
relation table map ==> Address will be a Address table, Emp table should have rest of the info.

Appreciate any of you share thoughts / code around this ?
I'm not sure if I understood your question but python has a powerful json module.

import json

my_str_json = '{"Emp" : {"K1" : "V1", "Address" : [], "K2" : "V2", "job" : { "K3" : "v3"}}}'
my_json = json.loads(my_str_json)
print(my_json["Emp"]["job"]["K3"]) # 'v3'
Thanks for the reply.

import json

my_str_json = '{"Emp" : {"K1" : "V1", "Address" : [], "K2" : "V2", "job" : { "K3" : "v3"}}}'
my_json = json.loads(my_str_json)
print(my_json["Emp"]["job"]["K3"]) # 'v3'

I was trying to make JSON parsing as meta data ( configuration) driven. As you see in the above code, in order to get value of "K3", we have slicing rule as my_json["Emp"]["job"]["K3"]. instead of hard coding, i was thinking of passing slicing rule from a config file and python code reads the config and apply slicing rule on respective python dict.
eg:
Config file :
rule1 : ["Emp"]["job"]["K3"]

in the code:
import json

my_str_json = '{"Emp" : {"K1" : "V1", "Address" : [], "K2" : "V2", "job" : { "K3" : "v3"}}}'
my_json = json.loads(my_str_json)
print(my_json[rule1]) # 'v3'

when i tried that, im getting KeyError though respective key present in the dictionary. but the same is working for single dimension slicing but not multi dim.
Appreciate if you guys share some light whether its really possible?
Just an initial idea...

import json


def get_value(idx, d):
    if isinstance(d, dict):
        if my_keys[idx] in d:
            return get_value(idx + 1, d[my_keys[idx]])
    else:
        return d
    return "Not found!"


my_str_json = '{"Emp" : {"K1" : "V1", "Address" : [], "K2" : "V2", "job" : { "K3" : "v3"}}}'
my_json = json.loads(my_str_json)
my_keys = ["Emp", "job", "K3"] # you'll have to create this list from the config file
value = get_value(0, my_json)
print(value)