I can't parse a json file for item values, could someone help me out ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Nirha
//Json parser

extends Node

var item_data: Dictionary

func _ready():
	
	item_data = _LoadData("res://Data/ItemData.json")

func _LoadData(file_path):
	var json_data
	var file_data = File.new()
	
	file_data.open(file_path, File.READ)
	json_data = JSON.parse(file_data.get_as_text())
	file_data.close()
	return json_data.result



//ItemData.json
{
	"Tree Branch": {
		"ItemCategory": "Resource",
		"StackSize": 99,
		"Description": "A sturdy tree branch that can be used for crafting."
	},
	"Potion": {
		"ItemCategory": "Consumable",
		"AddHealth": 5,
		"AddEnergy": 32,
		"StackSize": 99,
		"Description": "It smells like medicine."
	},
	"Iron Sword": {
		"ItemCategory": "Sword",
		"ItemAttack": 3,
		"ItemSpeed": 0.75,
		"StackSize": 1,
		"Description": "Quite a rusty sword, but should be able to get the job done."
	}
}



//Item.gd

extends Node2D

var item_name
var item_quantity

func _ready():
	var rand_val = randi() % 3
	if rand_val == 0:
		item_name = "Iron Sword"
	elif rand_val == 1:
		item_name = "Tree Branch"
	else:
		item_name = "Potion"
	
	$TextureRect.texture = load("res://item_icons/" + item_name + ".png")
	var stack_size = int(JsonData.item_data[item_name]["StackSize"])
	item_quantity = randi() % stack_size + 1
	
	if stack_size == 1:
		$Label.visible = false
	else:
		$Label.text = String(item_quantity)
		
func add_item_quantity(amount_to_add):
	item_quantity += amount_to_add
	$Label.text = String(item_quantity)
	
func decrease_item_quantity(amount_to_remove):
	item_quantity -= amount_to_remove
	$Label.text = String(item_quantity)

What is the error you get? (Or is there one?)

1234ab | 2021-04-10 13:43

There is no error. It just won’t parse the data

Nirha | 2021-04-10 18:23

:bust_in_silhouette: Reply From: beaverusiv

My save game loading code which works perfectly:

func read_file():
    var save_game = File.new()
    if not save_game.file_exists("user://savegame.save"):
        state = empty_save
        return

    save_game.open("user://savegame.save", File.READ)
    state = parse_json(save_game.get_as_text())
    save_game.close()

Would this work with my code ?

Nirha | 2021-04-17 23:10

You will have to put it in and adjust it if necessary, but it wil work

beaverusiv | 2021-04-18 07:40