Ask coding questions

← Back to all posts
Value not writing to correct key in JSON
RogueHalo (402)

Hey There,

So I'm trying to increment a value in my JSON file. The idea is that I can call a function (dayInc() which is in and it will increment the value of the key called "days" (in stats.json)

However, it just seems to be writing to the end of the JSON file where I'm trying to increment the value of the key "days"

Not sure what is going wrong with it though, any help would be appreciated!

Note: As you can see (from what the program outputs), it increments fine in the python file, just not in the JSON file.

Answered by brandosha (12) [earned 5 cycles]
View Answer
brandosha (12)

Dump the entire JSON object back into the file

RogueHalo (402)

@brandosha You mean the variable "data"?

brandosha (12)

@JacksonCowie yes, you are currently only writing the value at the key into the file but you want to overwrite the entire object with the new value

RogueHalo (402)


    "name": "Jackson",
    "state": "University",
    "health": 100,
    "cash": 0,
    "days": 0
}{"name": "Jackson", "state": "University", "health": 100, "cash": 0, "days": 1}

That's the resulting JSON file

brandosha (12)

@JacksonCowie Ok. It looks like you open the file, read it - which moves the stream to the end of the file - and then write starting at the end of the file. Use file_object.truncate(0) and before the json.dump To clear the file and then write starting from the beginning of the file.

RogueHalo (402)

@brandosha Yes! Thank you! It worked.