External / Online JSON issues using Godot | Godot 4

Godot Version | v-4.2.1 stable

Hello !
I’m new to Godot and I’m developping an app that needs an online database. For this I’m using JSON coupled with the HTTPRequest in Godot. I followed tutorials and always have the same issue. The response = 0 and it returns "Invalid get index ‘question’ (on base :‘int’).

Here’s my GDScript code :

extends Node

func _button_pressed(button):
    $HTTPRequest.request(url)

func _on_http_request_completed(result, response_code, headers, body):
	var json = JSON.new()
	var response = json.parse(body.get_string_from_utf8())
	print(response)
	
	if response["question"].has("Abracadabra"):
		print("YES")
	else:
		print("NO")

And here’s what my JSON look like :

{"enigmas" :[
    {
        "answer": "8",
        "fakeAnswer1": "5",
        "fakeAnswer2": "3",
        "fakeAnswer3": "88",
        "id": 1,
        "question": "Abracadabra",
        "solution": "Godot is fire but I hate JSON"
    }
]

My goal here is to get the console print “YES”.
Every kind of help is welcome !
Thanks a lot ! :hugs:

json.parse just returns an error code, it doesn’t return the data itself.
Try something like:

var error_code = json.parse(body.get_string_from_utf8())
if error_code == OK:
    var data = json.data

It works fine thanks ! And how do I select precisely and not all the infos in the JSON File ?
Thanks !

You’re welcome :slight_smile:

Well data is a dictionary, you can access anything in it like you’d normally access elements of a dictionary. Something like:

var enigmas = data.enigmas
var first_enigma = enigmas[0]
if first_enigma.question == "Abracadabra":
	print("YES")
else:
	print("No")
1 Like

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