+1 vote

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 "File.store..." functions seem to be more appropriate for storing data in empty files.
How can I modify this file from GDScript?

in Engine by (515 points)

1 Answer

+2 votes
Best answer

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 = File.new()
f.open("data.json", File.READ)
var json = JSON.parse(f.get_as_text())
f.close()
var data = json.result

# Modify
data["year"] = 2012

# Save
f = File.new()
f.open("data.json", File.WRITE)
f.store_string(JSON.print(data, "  ", true))
f.close()
by (27,829 points)
selected by

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.