Topic was automatically imported from the old Question2Answer platform.
Asked By
Sha6er
hello,
I am making a simple inventory and i have a problem
am making a global file that contains empty dictionary that receives data from other script
what i want is to save this dictionary to json file then when i play the game again it read from json back to global dictionary.
i think it is complicated but maybe someone have a different idea to share it with me.
here is the global file am talking about
extends Node
const FILE_NAME = "user://game-data.json"
var inventory = {} # here i want it to read from json file
func _ready():
var file = File.new()
if file.file_exists(FILE_NAME):
file.open(FILE_NAME, File.READ)
var data = {}
var text = file.get_as_text()
data = parse_json(text)
inventory = data
file.close()
func save_game():
var file = File.new()
file.open(FILE_NAME, File.WRITE)
file.store_line(to_json(inventory))
file.close()
it works when i save it to json and give me this result
{"0":["Potion",4]}
the json result explained —> slot_index: [item_name, item_quantity]
I don’t understand what you’re asking… your code works!
Your code works just fine, but what I would suggest doing is saving your data as a resource file for godot, see this tutorial to do it.
thanks for the reply. it works when saving and when i load it print the results but i cannot figure out how to load all the results back into the Global dictionary.
var inventory = {} # here i want it to read from json file
Sha6er | 2020-09-25 17:06
inventory = data
Your line there does that!
exuin | 2020-09-25 17:52
Look to make it easier for you to understand my issue
The inventory dict gets data from other script example
{"0":["Potion",4], "1":["sword ",1]}
So everything is fine. Then i want to save this dictionary to load it back when i play my game again. I used json file and it saves the data as i mentioned earlier also it loads all the results back when i print data it shows data . Everything is ok but the issue is not loading the data back inside the ‘global.inventory dictionary’ again. Maybe the data got converted or something else making it having this issue. However thanks for thinking of a solution with me and have a good day.
Sha6er | 2020-09-25 18:48
Sorry, I’m really confused. If the issue isn’t that you can’t load the data from the json file, what is the issue, then?
i found a solution for this problem. so am sharing this for anyone in need
just add when saving var2str
file.store_line(to_json(var2str(inventory)))
and when loading str2var
inventory = str2var(data)
this fixed my issue it was parsing the object as a text so godot can’t read it that is why it wouldn’t show in inventory slots after loading but by using var2str and str2var it helped saving and loading the object as it is.