0

Есть json файл:

{
"users":[
{"id": 1,
"cash": 100},
{"id": 2,
"cash": 300},
{"id": 3,
"cash": 500}
]}

Я пытаюсь поменять значение одного из ключей:

with open("data.json", "w") as file:
    obj = json.load(file)
    obj["users"][0]["cash"] = 50
    json.dump(obj,file)

Но оно просто создает новый обьект:

{
"users":[
{"id": 1,
"cash": 100},
{"id": 2,
"cash": 300},
{"id": 3,
"cash": 500}
]}{"users": [{"id": 1, "cash": 50}, {"id": 2, "cash": 300}, {"id": 3, "cash": 500}]}

помогите пожалуйста

2 ответа 2

0

откройте файл для чтения и запишите в переменную, после чего откройте в режиме записи и запишите изменения

with open('data.json', 'r') as f:
    obj = json.load(f)
    obj["users"][0]["cash"] = 50
    with open('data.json', 'w') as f:
        json.dump(obj, f)
0

Можно сделать это за одно открытие, выглядеть будет так:

import json


with open("data.json", "r+") as file:
    obj = json.load(file)
    obj["users"][0]["cash"] = 50

    file.seek(0)
    json.dump(obj, file)
    file.truncate()

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.