Created
November 28, 2021 05:49
-
-
Save jj-github-jj/700847002b68bbb5f7cc87f5ff066045 to your computer and use it in GitHub Desktop.
json to class for autocomplete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# for key,value in x.iteritems(): | |
# new_key = key.replace(" ","_") | |
# del x[key] # Deleting Previous Key | |
# x[new_key] = value # Adding Modified key | |
# for key,value in x.iteritems(): | |
# new_key = key.replace(" ","_") | |
# del x[key] # Deleting Previous Key | |
# x[new_key] = value # Adding Modified key | |
def convert(k): | |
k=k.replace(':',"_") #replace : with _ since ":" not acceptable in syntax | |
k=k.replace("(","_") | |
k=k.replace(")","_") | |
k=k.replace("/","_") | |
k=k.replace("-","_") | |
return k.replace(' ', '_') #replace space with underscore in string k | |
def change_keys(obj, convert): | |
""" | |
Recursively goes through the dictionary obj and replaces keys with the convert function. | |
""" | |
if isinstance(obj, (str, int, float)): | |
return obj | |
if isinstance(obj, dict): | |
new = obj.__class__() | |
for k, v in obj.items(): | |
new[convert(k)] = change_keys(v, convert) | |
elif isinstance(obj, (list, set, tuple)): | |
new = obj.__class__(change_keys(v, convert) for v in obj) | |
else: | |
return obj | |
return new | |
#------------- usage. replace with your json file ---------------- | |
import json | |
from types import SimpleNamespace | |
| |
fpath=r"C:\temp\data 5842 dibwFri_ Sep 10_ 2021_5_12 PM.json" | |
f=open(fpath) | |
dnew=json.load(f) #json.dumps is inverse of loads | |
dnew=change_keys(dnew,convert) #remove invalid characters with underscores in names | |
dnew=json.loads(json.dumps(dnew), object_hook=lambda d: SimpleNamespace(**d)) | |
#--------------- | |
# Turns a dictionary into a class | |
# type variable name such as t4. and wait for the class attributes to appear in editor using Kite or other language processors | |
class Dict2Class(object): | |
def __init__(self, my_dict): | |
for key in my_dict: | |
key2=key.replace(" ","_") #key2 for valid names without spaces for object attributes | |
key2=key2.replace(":","_") | |
setattr(self, key2, my_dict[key]) | |
def print_attributes (d): | |
[print (x) for x in dir(d) if "__" not in x ] | |
# ------------ display JSON file in heirachical format | |
import json | |
from IPython.display import display, JSON | |
file_path=r"C:\temp\test_lv_json_device_data" | |
with open(file_path) as f: | |
my_dict= json.load(f) | |
display(JSON(my_dict)) #show json heirarchy in jupyter notebook | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment