How to modify a JSON file?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By DodoIta

Hi everyone,
I have a JSON file structured like this:

  "last_req": {
    "year": "2018",
    "month": "6",
    "day": "25",
    "hour": "12",
    "minute": "18"

I can open the file and read it with no problems. But I’m trying (with no success) to save some changes to this file. The various “…” functions seem to be more appropriate for storing data in empty files.
How can I modify this file from GDScript?

:bust_in_silhouette: Reply From: Zylann

To modify a JSON file, you need to load it, modify its data, and then save it. That is, you need to overwrite the existing file with the new data:

# Load
var f ="data.json", File.READ)
var json = JSON.parse(f.get_as_text())
var data = json.result

# Modify
data["year"] = 2012

# Save
f ="data.json", File.WRITE)
f.store_string(JSON.print(data, "  ", true))

I’ve always overlooked JSON.print.
Thank you a lot, it works perfectly.

DodoIta | 2018-06-26 15:07