Need help reading data from a json file?

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

Hello, I am trying to read data from a json file, then have entry from that file display it into a Label so far I am unsuccessful. Below is my json file and below that is the code I am using. please help?

 {
  "1": {
    "id": 1,
    "name": "Warlord",
    "series": 1,
    "mana": 2,
    "descr": "Attack is straight forward, so is Defense.",
    "attack": 3,
    "defend": 2
  },
  "2": {
    "id": 2,
    "name": "Crusher",
    "series": 1,
    "mana": 4,
    "descr": "Attack is a major strength of the character.",
    "attack": 8,
    "defend": 2
  },
  "3": {
    "id": 3,
    "name": "Max",
    "series": 1,
    "mana": 4,
    "descr": "A very powerful character for attacking and defending.",
    "attack": 7,
    "defend": 7
  }
}


var file = File.new()
file.open("res:/TradingCardGame.json", file.READ)
var json = file.get_as_text()
var json_result = JSON.parse(json)
file.close()
get_node("Label").set_text(json_result[["1"]["name"][1]])

Edited for code formatting

Zylann | 2018-02-10 17:09

:bust_in_silhouette: Reply From: Zylann

Looks like you have a typo in your code:

file.open("res:/TradingCardGame.json", file.READ)
Should be
file.open("res://TradingCardGame.json", file.READ)
If you look in the console Godot should have told you already that your path is invalid.

Also, JSON.parse doesn’t return the JSON data straight away, it returns a JSONParseResult (see the docs).

So instead of:
var json_result = JSON.parse(json)
You can write:
var json_result = JSON.parse(json).result

But note that JSONParseResult can also give you infos about parsing errors.

Finally, 3rd problem in your code:
json_result[["1"]["name"][1]])
Should be:
json_result["1"]["name"][1])
I am not sure what you expect for the last [1], because ["1"]["name"] will give you a string, not an array.

Thanks for you answer Zylann.

I think the docs are wrong.
In this link:
JSONParseResult — Godot Engine (3.0) documentation in English

The code:
p = JSON.parse(‘[“hello”, “world”, “!”]’)
if typeof(p) == TYPE_ARRAY:
print(p[0]) # prints ‘hello’
else:
print(“unexpected results”)

Does not print “hello” as advertised, because the line:
p = JSON.parse(‘[“hello”, “world”, “!”]’)
implies JSON.parse returns the JSON data straight away, which it doesn’t.
The correct code snippet should be:

p = JSON.parse(‘[“hello”, “world”, “!”]’).result
if typeof(p) == TYPE_ARRAY:
print(p[0]) # prints ‘hello’
else:
print(“unexpected results”)

danieldourado_2 | 2018-02-28 00:48