Hello,
I’m trying to parse a PHP file with generated JSON data in it.
The JSON have names of players and links to images that belong to their characters
extends Control
@onready var http := HTTPRequest.new()
var api := "https://somewebpage.com/api.php"
var img_link : String
var object_id := 0
func _ready():
add_child(http)
http.request_completed.connect(self._http_request_completed)
http.request(api)
func _http_request_completed(result, response_code, headers, body):
var json = JSON.new()
json.parse(body.get_string_from_utf8())
img_link = json.get_data()[object_id].character
_download_image()
func _download_image():
if img_link.get_extension() == "jpg":
http.download_file = "img/" + img_link.get_file()
http.request(img_link)
The script above does the following:
connects to my api.php
parses it for links
downloads an image of selected player’s character
currently there are 2 players in json = 2 character images
using object_id variable I switch between json objects
the problem is after downloading an image the game freezes with a following error:
Invalid get index ‘0’ (on base: ‘Nil’)
and targets me to the line 17 of the script, which is:
img_link = json.get_data()[object_id].character
even though it shows this line as a breaking point, the download image function still uses the data stored in it and I get the image I need, I just don’t know how to get rid of the freeze and what the error means.
Your json data doesn’t match the structre you assume it matches. It probably starts with a dictionary {} instead of an array []. print(json.get_data()) to see exactly what you are receiving.
Yeah, access it correctly. I can’t tell you what the correct way is because you didn’t show your json structure. I can only guess so much with my crystal ball.