JSON Godot 3.x How can I print() "TEST"?

Godot Version

v3.5.3(Linux)

Question

How can I print() “TEST”?

ERROR: Error parsing JSON at line 1: Expected key index.js:369:18

at: parse (core/bind/core_bind.cpp:3267) - Error parsing JSON at line 1: Expected key index.js:369:18

extends Node

var my_http_request := HTTPRequest.new()

func _ready():
	add_child(my_http_request)
	my_http_request.connect("request_completed", self, "_my_http_request_completed")
	
	_my_http_request()

func _my_http_request():
	var my_error = my_http_request.request(Setting.gameUrl + "/test.json")
	
	if my_error != OK:
		push_error("HTTPリクエスト中にエラーが発生しました。")
		
func _my_http_request_completed(my_result, my_response_code, my_headers, my_body):
	var my_response = JSON.parse(my_body.get_string_from_utf8())
	print("my_result: " + str(my_result))
	print("my_response_code: " + str(my_response_code))
	print("my_headers: " + str(my_headers))
	print("my_body: " + str(my_body))
	print("my_response: " + str(my_response))

test.json

{
    {"foo":1,"bar":"TEST"},
}

Your JSON is not in a valid JSON format.

[
    {
        "foo": 1,
        "bar": "TEST"
    }
]

This would be valid.

The extra comma.

test.json

[
    {
        "foo": 1,
        "bar": "TEST"
    }
]

The error has disappeared.

But it can not print() “TEST”.

How can I print() “TEST”?

Going by your code, if the “my_response” variable contains the parsed json string, and it looks like it might (see: JSON — Godot Engine (3.5) documentation in English), then you can print “TEST”, aka the value for the key “bar” with the following code:

print(my_response.bar)
1 Like
print(my_response.bar)

Runtime error.
Invalid get index ‘bar’ (on base: ‘JSONParseResult’).

Please research the documentation for your specific version of the engine. I’ll leave the relevant information here:

print("my_response.result[0].bar: " + str(my_response.result[0].bar))

This is how I was able to display “TEST”.

I appreciate your help.

1 Like