D
D
Dmitry Shevchenko2022-03-17 20:56:27
Python
Dmitry Shevchenko, 2022-03-17 20:56:27

How to write data to JSON along the way?

I have a json representing a dictionary filled with nested dictionaries. I want to write a function to which I could somehow pass the entire path so that it writes certain data along this path.

def user_write (chat, par,val):
    users = {}
    with open('data.json', 'r', encoding='utf-8') as file:
        users = json.load(file)
    with open('data.json', 'w', encoding='utf-8') as file:
        users[chat][par] = val
        json.dump(users, file, indent=4,ensure_ascii=False)

such a function copes if without attachments, but if I have a list in the list, and inside it there is another one, then I don’t know how to implement this ... Please tell me how to pass the path as a variable and get a specific key pair from it meaning?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Leonid, 2022-03-17
@bravebug

List elements can be accessed by index: user_list[3][0][2]
What exactly is the problem? What is the error text and sample data?

V
vilinyh, 2022-03-17
@vilinyh

def set_value(data, index, value):
    key = index.pop(0)
    if len(index):
        if key in data:
            data_key = data[key]
        else:
            data_key = {}
        data[key] = set_value(data_key, index, value)
    else:
        data[key] = value
    return data


users_list = {0: {'name': 'vasya'}}

set_value(users_list, [0, 'age'], 16)
# {0: {'name': 'vasya', 'age': 16}}

Surely there is a more elegant solution or a ready-made helper, but I'm zero in python.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question