How do I edit a JSON file using scripts?

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

Hi,

I recently picked up godot for a school project. Here is the JSON I want to use in it (date will eventually be meaningful, but for now it is represented by an integer):

{
"words": [
	{
		"word": "word",
		"def" : "definition",
		"date" : 100
	}
]

}

I want it to involve saving and loading data from a JSON file to store data. So far, I’ve learned how to grab data using:

func load_json():
  var file = FileAccess.open("res://words.json", FileAccess.READ)
  var js = JSON.new()
  js.parse(file.get_as_text())
  var data = js.get_data()
  dict = data
  file.close()

However, I couldn’t find results to save additional dictionaries and change existing data in the JSON. The results I did find were mostly for outdated versions. Here is my attempt at a saving function (meant to append a new dictionary to words.json):

func append_words(new_dict: Dictionary):
if (check() == false): # check(): checks if my LineEdit nodes contain text to add into the new "word" and "def" values of the new dictionary to be appended
	%OUTPUT.text = "no input, try again."
else:
	load_json()
	var file = FileAccess.open("res://words.json", FileAccess.WRITE)
	var js = JSON.new()
	file.store_var(new_dict)
	file.close()

When I run the code and look in the words.json file, it changes to a signle “$” and gives the warning:

core/io/json.cpp:614 - Error parsing JSON file at ‘res://words.json’, on line 0: Unexpected character.

Help would be greatly appreciated and thanks in advance!

Do you have any insight where that error occurred? Normally, that’s an error reading json (parsing) not writing it (serializing). Without seeing your json file it’s hard to say if it is valid. It seems like line 4 in your first script is causing the issue, but stack would help to verify for you. If you run the code above andcheck() returns true and words.json is not valid json, you’d get this error.

EDIT You can test if you json is valid with a website such as this one.

Tom Mertz | 2023-05-23 01:28