1

I have a list of lists where each list is the full path of where to modify the value.

import json
with open('main_data.json', 'r') as f:
    di = json.load(f)

lists = [[0, 'data', 'Hierarchical Namespace', 'LRS', 0, 'Archive'], [0, 'data', 'Hierarchical Namespace', 'LRS', 1, 'Archive'],...]

what I want to do is for each list value to a di['list_path']=json.loads(value)

so for the first 2 lists would be (if I am to do it manually)

v1 = di[0]['data']['Hierarchical Namespace']['LRS'][0]['Archive']
di[0]['data']['Hierarchical Namespace']['LRS'][0]['Archive'] = json.loads(v1)
v2 = di[0]['data']['Hierarchical Namespace']['LRS'][1]['Archive']
di[0]['data']['Hierarchical Namespace']['LRS'][1]['Archive'] = json.loads(v2)
...
1

1 Answer 1

1

found something for you, using exec function:

# your original list
lists = [
    [0, 'data', 'Hierarchical Namespace', 'LRS', 0, 'Archive'], 
    [0, 'data', 'Hierarchical Namespace', 'LRS', 1, 'Archive'],
]

# this is the formated version (how would you see it as a string)
formatted_lists = []
for values in lists:
    formatted_values = []
    for value in values:
        if isinstance(value, str):
            # using __repr__ i cant see the string quotes inside a string
            formatted_values.append(value.__repr__())
        else:
            # i need to convert the int to string
            formatted_values.append(str(value))
    
    # template useful for executing it
    key_template = f"[{']['.join(formatted_values)}]"
    formatted_lists.append(key_template)

# iterating through templates and executing what you wanted
for formatted_value in formatted_lists:
    code = "di{} = json.loads({})".format(formatted_value, formatted_value)
    print(code)
    exec(code)

output (what is executed)

di[0]['data']['Hierarchical Namespace']['LRS'][0]['Archive'] = json.loads([0]['data']['Hierarchical Namespace']['LRS'][0]['Archive'])
di[0]['data']['Hierarchical Namespace']['LRS'][1]['Archive'] = json.loads([0]['data']['Hierarchical Namespace']['LRS'][1]['Archive'])
Sign up to request clarification or add additional context in comments.

1 Comment

you are asking the execute a huge index operator accessing multiple times without writing by hand. ofc its not the prettiest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.