How to correctly parse a JSON with multiple objects?

Godot Version

v4.2.1.stable.official [b09f793f5]

Question

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:

  1. connects to my api.php
  2. parses it for links
  3. 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.

thanks in advance for any help

p.s: sorry for my possible broken english

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.

1 Like

yep, is there an easy way to fix it by not editing the php?

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.

sorry my bad, here is what I get from generating json after connecting to my DB via php api:

[ { "player": "Jason", "character": "https:\/\/somewebpage.com\/img\/wolverine.jpg" }, { "player": "Lola", "character": "https:\/\/somewebpage.com\/img\/deadpool.jpg" } ]

here is the php that generates the json structure above:

if($connection){
    $sql = "SELECT * FROM `players`";
    $result = mysqli_query($connection, $sql);
    if($result){
        header("Content-Type: JSON");
        $i=0;
        while($row = mysqli_fetch_assoc($result)){
            $response[$i]["player"] = $row["Player"];
            $response[$i]["character"] = $row["Character"];
            $i++;
        }
        #echo json_encode($response);
        echo json_encode($response, JSON_PRETTY_PRINT);
    }
}else{
    echo "DB connection fail";
}

You’re not doing error checking.

var error = json.parse(body.get_string_from_utf8())
if error == OK:
	img_link = json.get_data()[object_id].character
	_download_image()
else:
	print(json.get_error_message())
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.