Invalid get index while reading information from JSON files

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

I’m trying to make a script that reads JSON files and edits variables if a specific key inside of the JSON file != null. When the key != null, it’s a dictionary with a few arrays inside of it, with extra keys that I use to specify what I want to change.

[{"Text" : "This is what the JSON looks like", "Options" : null},

{"Text" : "This is what the file looks like when I want to edit options",    "Options" : [{"Option1" : "Random value"}, {"Option2" : "Value2"}]}]

This way, if the player picks an option, I can set up the appropriate variable change inside of the JSON so that everything can be handled in one script .

The issue that I’m running into is that the script can read the normal array (example 1) just fine, but when I isolate the “Options” key to read it’s values;

if json_data.Options != null:
   var player_options = json_data.Options
   parameter1 = player_options.Option1

I get an invalid get index error no matter what.

Invalid get index ‘option1’ (on base: ‘Dictionary’).

I’m really new to coding and working with this sort of thing, any insight would be appreciated.

:bust_in_silhouette: Reply From: chesse

Hi iris,

your json definition creates the following structur in godot

│
├ [0]
│    ├ "Text": "This is what the JSON looks like",
│    └ "Options": null
└ [1]
     ├ "Text": "This is what the file looks like when I want to edit options",
     └ "Options":
          ├ [0]
		  │    └ "Option1": "Random value"
		  └ [1]
		       └ "Option2": "Value2"

So the “Options” in the second array element is also an array.

Option1 and Option2 are accessible by a numerical index

parameter1 = player_options[0].Option1
parameter2 = player_options[1].Option2

Or you can iterate through the array.

If the elements in your “Options” list are unique, than you can do it without an “Options” array

[
	{
		"Text": "This is what the JSON looks like",
		"Options": null
	},
	{
		"Text": "This is what the file looks like when I want to edit options",
		"Options": {
			"Option1": "Random value",
			"Option2": "Value2"
		}
	}
]

Than you can access them diretly

for json_data in jsonData:
	if json_data.Options != null:
		var player_options = json_data.Options
		parameter1 = player_options.Option1
		parameter2 = player_options.Option2