Extract from String, how to cut from "[" to "]" and stuff it into an Array?

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

Im trying to extract text from a longer string to multiple strings and then I want to put them into an array with GDScript.

Also you may notice that the string (down below) is actually a Dictionary, if you know how I can replace an empty Dictionary with that string feel free to tell me because if so I wont have to extract those strings and that also would solve my problem.

The String: “{1:[Bones, 3], 30:[Iron Sword, 3]}”
Now I need to extract it like this “Bones, 3” > to array > “Iron Sword, 3” > to array
I looked through the String Documentation and I guess the only thing useful is “.rsplit()” but it will only look for one char and not two,

var some_string = "{1:[Bones, 3], 30:[Iron Sword, 3]}"
var some_array = some_string.rsplit("[", true, 1)
print(some_array.size()) # Prints 2
print(some_array[0]) # Prints "{1:[Bones, 3], 30:"
print(some_array[1]) # Prints "1:[Bones, 3], 30:[Iron Sword, 3]"

Then there is RegEx, I looked into it but before I try to learn its awkward syntax I thought I ask here if there is a relatively more easy way to “nab segments” of a long one liner string so that they can be put in an array, thanks in advance and I hope my question(s) is/are understandable.

:bust_in_silhouette: Reply From: Afely

You should be able to just parse the whole string with parse_json() and then getting the arrays from there is easy.

Somehow something got messed up while handling those variables, they probably always changed types, but after ‘forcing’ it I got to work, I’ll mark your answer as best because your words inspired me to google for my answer, thanks.


Todog000 | 2021-05-30 21:06

:bust_in_silhouette: Reply From: annemarietannengrund

hey, i just added a button to my project which does a json decode.
it seems that the (valid) numerical key gave me a hickup in godot, so i turned them into strings. saving json keys as strings is a default option when encoding.

hope the example helps you figure out how to navigate the array and access values

var text_json = '{"1":["Bones", 3], "30":["Iron Sword", 3],}'
var result_json = JSON.parse(text_json)
var result = {}

if result_json.error == OK:  # If parse OK
	var data = result_json.result
	for key in data.keys():
		print('key: ', key,', Weapon: ', data[key][0],', Damage: ', data[key][1])
else:  # If parse has errors
	print("Error: ", result_json.error)
	print("Error Line: ", result_json.error_line)
	print("Error String: ", result_json.error_string)

thanks that answered my other question.

Todog000 | 2021-05-30 21:08