How to store dictionary as JSON file? (Formatted)

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

Hello!

I’ve got a question and would appreciate the help. My game uses an external JSON file to store certain key-value pairs that the game must remember between runs. In the initial file, i store the data one key-value pair per line. Like this:

{“key1” : “value1”,
“key2”:“value2”,
“key3”,“value3”}

I can read and parse the file using:

var file = File.new()
file.open(filepath, file.READ)
var json=file.get_as_text()
var json_result = JSON.parse(json).result
file.close()

However when i write it back using:

file.open(filepath, File.WRITE)
file.store_line(to_json(json_result))
file.close()

The resulting file will look like this:

{“key1”:“value1”,“key2”:“value2”,“key3”,“value3”}

Which works and parsable again… but simply hurts my eyes to look at if it will have more records.

And if I use this to write it back:

file.open(filepath, File.WRITE)
file.store_var(json_result)
file.close()

Then I the file will look something like:

NULNULNUL Key1 NUL NULL Value1 NUL.
NULNUL Key2 NULNUL Value2 NUL NUL

Is there a way to get back the original file structure?

Thanks in advance folks!

https://www.youtube.com/watch?v=g_7hgbxjtLY

Landroval | 2023-02-12 16:26

:bust_in_silhouette: Reply From: SteveSmith

Instead of to_json(), if you use JSON.print() you can format the output in a less eye-hurting way. See JSON — Godot Engine (stable) documentation in English

You are a saint! It worked. For any internet archaeologists stumbling upon this thread in the future; the solution that worked for me was:

file.open(filepath, File.WRITE)
file.store_line(JSON.print(json_result, "\t"))
file.close()

GarlicPerson | 2022-11-21 12:48