python script builds ierarchy of jsons - level 1, 2 ,3, 4 , save result, child, parent…
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
python
script builds ierarchy of jsons - level 1, 2 ,3, 4 , save result, child, parent to new DF
Fix error with wrong parents, example
{'categoryID': 111, 'params': []} -- {'categoryID': 1, 'params': []}
it can't be with different 'categoryID'
import json import pandas as pd
Sample data
data = [ ‘{“categoryID”:10,“params”:{}}’, ‘{“categoryID”:10,“params”:[{“id”:5,“value”:“MjA=”}]}’, ‘{“categoryID”:10,“params”:[{“id”:5,“value”:“MjE=”}]}’, ‘{“categoryID”:10,“params”:[{“id”:5,“value”:“MjI=”}]}’, ‘{“categoryID”:10,“params”:[{“id”:5,“value”:“MjA=”},{“id”:157609,“value”:“MzI1OTUxMw==”}]}’, ‘{“categoryID”:10,“params”:[{“id”:5,“value”:“MjA=”},{“id”:157609,“value”:“MzI1OTUxNA==”}]}’ ]
Create a DataFrame
df = pd.DataFrame({‘jsons_string’: data})
Parse JSON strings into dictionaries
df[‘json_dict’] = df[‘jsons_string’].apply(json.loads)
def is_parent(parent_dict, child_dict): # Check if parent params is empty dictionary if parent_dict.get(‘params’) == {}: return True
code# For non-empty parent params if isinstance(parent_dict.get(‘params’), list): parent_params_set = set((d[‘id’], d[‘value’]) for d in parent_dict[‘params’]) child_params_set = set((d[‘id’], d[‘value’]) for d in child_dict.get(‘params’, [])) return parent_params_set.issubset(child_params_set) return FalseFunction to find the parent of a given JSON dictionary
def find_parent(json_dict, json_list): potential_parents = [ jd for jd in json_list if is_parent(jd, json_dict) and jd != json_dict ] if potential_parents: # Return the parent with the largest number of params return max(potential_parents, key=lambda jd: len(jd.get(‘params’, []))) return None
Find parents for each JSON dictionary
json_list = df[‘json_dict’].tolist() df[‘parent_json_dict’] = df[‘json_dict’].apply(lambda jd: find_parent(jd, json_list))
Convert parent JSONs back to string
df[‘parent_json_string’] = df[‘parent_json_dict’].apply(lambda x: json.dumps(x) if x else None)
Drop the temporary dictionary columns
df = df[[‘jsons_string’, ‘parent_json_string’]]
Save to CSV
df.to_csv(‘rez15.csv’, index=False)
Display the result
print(df)
- Assistant
- User
good! try to make algoritm faster
- Assistant