JSON has one kind of number and only text keys, so JSON.parse_string() gives every number back as a float and every dictionary key as a String. In our Godot 4.7 test 5 coins came back as 5.0 and the label said Coins: 5.0, a farm plot saved under Vector2i(2, 3) was no longer found, and an item saved under the ID 7 was only found as the text "7". Writing the file with JSON.from_native() and reading it with JSON.to_native() gave back the int 5, the Vector2i key and the int key.
The code
Save it as json_save.gd and use it in place of your own file code: const SaveJson := preload("res://json_save.gd"), then SaveJson.write("user://save.json", data) and var data = SaveJson.read("user://save.json", {}). read() gives back the fallback when the file is missing or broken, so a first launch or a save cut off halfway does not crash the game. from_native() and to_native() need Godot 4.4 or later.
extends RefCounted
## Saves and loads game data as JSON and gives back the same types you saved.
## JSON.stringify() + JSON.parse_string() turn every number into a float and
## every dictionary key into a String, so 5 coins load as 5.0, and farm plots
## keyed by Vector2i or items keyed by an int ID are no longer found.
## JSON.from_native() / JSON.to_native() (Godot 4.4 and later) store the type
## next to each value, so ints, Vector2i keys and Vector2 come back as they were.
## SaveJson.write("user://save.json", data)
## var data = SaveJson.read("user://save.json", {}) # {} if missing or broken
static func write(path: String, data) -> bool:
var f := FileAccess.open(path, FileAccess.WRITE)
if f == null:
return false
f.store_string(JSON.stringify(JSON.from_native(data), "\t"))
return true
static func read(path: String, fallback = null):
if not FileAccess.file_exists(path):
return fallback
var json := JSON.new()
if json.parse(FileAccess.get_file_as_string(path)) != OK:
return fallback # empty or broken file (json.get_error_message() says why)
return JSON.to_native(json.data)
What we measured
A save with 5 coins, day 12, a plot keyed by Vector2i(2, 3), an item keyed by the int 7, a 64-bit player ID 9007199254740993, a Vector2 spawn point and a list of seeds [3, 1, 4]. Two runs gave the same results.
JSON.stringify()thenJSON.parse_string(): coins was the float 5.0."Coins: " + str(coins)showed Coins: 5.0, and adding 1 showed 6.0.coins == 5was still true, but amatch coins:with a5:branch did not match.- The plot key came back as the String "(2, 3)" and
has(Vector2i(2, 3))was false. The item key came back as "7" andhas(7)was false. - The player ID came back as 9007199254740992, one less, because a float cannot hold every whole number that large. The spawn point came back as the String "(1.5, 2.0)" and the seeds as [3.0, 1.0, 4.0].
- The script: coins the int 5, Coins: 5, then 6, the match worked, both keys were found with their own types, the player ID was exact, the spawn point a Vector2 and the seeds ints.
- The file is bigger, 497 bytes against 133, because each value carries its type. It is still text you can open and read.
- A missing file and a file cut off in the middle both gave back the fallback {} without an error.
Why it happens
JSON is a text format from the web. It has numbers but no separate whole-number type, and object keys must be text. JSON.stringify() writes 5 as 5, but JSON.parse_string() cannot tell it was an int, so every number comes back as a float. A key that is not text is written as its text, (2, 3) or 7, and comes back as that text. Vector2 and other Godot types are not JSON at all, so they are written as text too. from_native() wraps each value with its type, and to_native() reads the type back.
What to change
- Already have saves made the old way? Read them once with
JSON.parse_string(), turn the values you need back withint()or your own keys, and write them again with the script. - Counting days for crops and seasons: a farming calendar. Time that passes while the game is closed: offline progress. Crops that show the wrong stage: growth stages.
Effects for the farm itself: Cozy VFX for Godot 4 has 29 ready-made effects for farming and life games, including fireflies, sleeping Zzz, hearts, music notes, steam and falling leaves.
Tested in Godot 4.7 with the Compatibility renderer.
Ready-made: Cozy VFX for Godot 4 has 29 ready-made effects for farming and life games, including fireflies, sleeping Zzz, hearts, music notes, steam and falling leaves.
More how-tos for Cozy VFX for Godot 4: Night-only effects when the night crosses midnight
More how-tos: Game systems
- Hover a 3D object inside a SubViewport
- A turned building that covers the cells it stands on
- An inventory that never loses an item and never overfills a stack
- Fire that spreads one cell per step, in every direction
- A pooled enemy that comes back as fresh as a new one
- An enemy that stops at the dead player and finds the respawned one
- Poison, burn and bleed that keep ticking when applied again
- XP, qi and gold that keep growing without going negative
- Count slot line wins with wilds in front
- Random directions spread evenly over a sphere or a cone
- Count a lap only when the car really went round
- Make a seed repeat: daily runs, replays and roguelike seeds
- Offline progress that counts the time the game was closed
- A chance roll without the long bad-luck streaks
- Check crafting recipes in any order, with the right counts
- Make HP and mana regen the same at any frame rate
- Damage over time with the right number of ticks
- Spawn enemies where the camera cannot see them
- Keep a chasing horde from stacking into one enemy
- Make the fish bite after the same wait at any frame rate
- Snap buildings to the right grid cell on both sides of the origin
- Make a cooking timer fire once, on time
- Pick from a weighted loot table with the right chances
- Level up as many times as the XP covers
- Walk a patrol guard to each point without overshooting
- Remove items from an Array while checking them, without skipping any
- Scatter spikes, roots or trees in a circle without overlaps
- Count and take crafting items from every stack
- Play random sounds and events without obvious repeats
- Pick the growth image so the ripe one shows exactly when the crop can be picked
- Turn a day counter into season, day and year without a day 0
- An enemy that dies once, however many hits land
- A fair shuffle you can replay
- A ghost that drives the lap at real speed
- A vision cone that does not flicker at the edge
- Move a group of units without a pile-up
- A sprinkler that waters a round patch
- A slot reel that always lands forward on the result
- A crowd of NPCs that never emote or bob in step
- A song position that moves on every frame
- Nodes your editor tool adds that stay in the scene