Only returning certain items from a JSON file based on conditions?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Robster
:warning: Old Version Published before Godot 3 was released.

Hi all,

I have a JSON file that describes my characters.

I have a character select screen and it loads the JSON data to feed the interface and allow you to cycle through the characters.

I want to be able to say, only show characters with X attributes and Y attributes.

So I have a function like so:

func loadCharacters(X, Y):
	var file = File.new()
	file.open("res://json/characters.json", file.READ)
	var text = file.get_as_text()
	dict.parse_json(text)
	file.close()
	
	#get how many are in results
	get_node("LabelCharactersNumTotal").set_text(str(dict.size()))

	# print something from the dictionary for testing.
	print(dict["3"])

So that all works as a base test which is fine. The print shows the contents of the third character.

How can I get ONLY characters that have X and Y that’s being passed to the function? I have ALL the character’s info in the dict but I want to now parse that or extract from there based on X and Y.

Any advice much appreciated.

:bust_in_silhouette: Reply From: Robster

…aaand I figured it out.

For future reference to help:

for i in dict:
	if dict[i]["x"] == x and dict[i]["y"] <= y:
		print(dict[i]["name"])

Above is just an example, but it should suffice to help guide. All the best.

@Robster, can you please show part of your .json file? I don’t understand how to control which character I want to use.

" # print something from the dictionary for testing.
print(dict[“3”])
"
How is it look in your .json file? “3” I mean.
Thank you

Gleb | 2017-11-07 21:08

Hey there sure. I would change it nowdays maybe, not sure, but this is what I did then:

{
  "0" : {
    "name": "James Rashburn",
    "image": "fighter-James.png",
    "hired": false,
    "salary": 6000,
    "level": 1,
    "confidence": 2
  },
  "1" : {
    "name": "Sarah Smith",
    "image": "fighter-Sarah.png",
    "hired": false,
    "salary": 14000,
    "level": 2,
    "confidence": 9
  }
}

Robster | 2017-11-08 22:26