Invalid set index

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

Just starting my adventure with coding so bear with me :smiley:
Why do i get this error:
Invalid set index ‘text’ (on base: ‘Label’) with value of type 'Nil."
I want the Label to display the text inside the json file.

here is the code simplified to the part that gives me the error:

extends Node
func _ready():
	var JsonText = text_json("text.json")
	$Label.text = JsonText

func text_json(filename):
	var file = File.new()
	file.open(filename, File.READ)
	var text = file.get_as_text()
	var data = parse_json(text)
	file.close()
	return data
	

How Your scene tree looks like ?

Vrzasq | 2019-08-25 22:52

Is the JSON file being properly interpreted and serialized to text? From the looks of it, the text_json() function is returning Nil.

Ertain | 2019-08-25 22:52

depending on where text.json is located, you likely want res://text.json, or res://path/to/text.json, where “path/to” should be changed to the actual path that your file lives at.

Eric Ellingson | 2019-08-26 00:03

:bust_in_silhouette: Reply From: Zylann

parse_json does not return a string, it returns an object representation of the JSON data. So according to the specification, it may be an array or a dictionary.

If you want to display JSON as text, either return text from your text_json function instead of parsing it, or re-print the JSON data as text using to_json(data).

Then, the result is currently nil probably because either your JSON file was empty, had a parsing error, or the file was not found.