How to Convert string "Vector 2" to Vector 2 data

Godot Version

4.4.1

Hi everyone,

I am learning about godot and trying to make a game.
I have a json file contains information like this:

{"#000345":["(958.0, 780.0)","(959.0, 780.0)","(960.0, 780.0)","(961.0, 780.0)","(958.0, 781.0)","(959.0, 781.0)","(960.0, 781.0)","(959.0, 782.0)"],"#00043A":["(1108.0, 1117.0)","(1109.0, 1117.0)","(1107.0, 1118.0)","(1108.0, 1118.0)","(1109.0, 1118.0)","(1107.0, 1119.0)","(1108.0, 1119.0)","(1109.0, 1119.0)","(1107.0, 1120.0)","(1108.0, 1120.0)","(1109.0, 1120.0)","(1107.0, 1121.0)","(1108.0, 1121.0)","(1109.0, 1121.0)","(1110.0, 1121.0)","(1111.0, 1121.0)","(1107.0, 1122.0)","(1108.0, 1122.0)","(1109.0, 1122.0)","(1110.0, 1122.0)","(1111.0, 1122.0)","(1112.0, 1122.0)","(1107.0, 1123.0)".... }

So when I want to use this dictionary with vector2, it returns me this error:

invalid access to property or key ‘x’ on a base object of type ‘string’

Here is where i got the error:

pixel_color_dict = import_json(“res://testcolorlookup.json”)
func get_polygons(image, region_color, pixel_color_dict):
var targetImage = Image.create(image.get_size().x,image.get_size().y, false, Image.FORMAT_RGBA8)
for value in pixel_color_dict[region_color]:
targetImage.set_pixel(value.x,value.y, “#ffffff”) # <= this line

var bitmap = BitMap.new()
bitmap.create_from_image_alpha(targetImage)
var polygons = bitmap.opaque_to_polygons(Rect2(Vector2(0,0), bitmap.get_size()), 0.1)
return polygons

func import_json(filepath):
var file = FileAccess.open(filepath, FileAccess.READ)
if file != null:
var json_string = file.get_as_text()
var out = JSON.parse_string(json_string)
#print(out)
return out
else:
print(“Failed to open file:”, filepath)
return null

Can you point out the wrong place and solution for this? I tried to follow this thread but it doesnt work (https://forum.godotengine.org/t/how-to-convert-string-to-vector2/72172/3)

Thanks in Advance!

You could switch your JSON:

{
  "#000345":
  [
    { x: 958.0, y: 780.0 },
    { x: 959.0, y: 780.0 },
   [...]
  ]
}

Otherwise, your vec2s are an array of strings:

"(958.0, 780.0)",
"(959.0, 780.0)",
[...]

If you want to keep it like that, you’ll need to split and parse the individual strings.

Edit:

1 Like

Because RegEx is painful to me…

func get_vector2_from_string(v_string:String)->Vector2: 
	var s:String = v_string.replace("(", "")
	s = s.replace(")", "")
	var x:float = float(s.get_slice(",", 0))
	var y:float = float(s.get_slice(",", 1))
	return Vector2(x,y)

Thanks you all.
I used exact same method that provided by @sancho in another thread yesterday, and it worked.

The code worked without error (with crashing :frowning: - which is not the topic here)
Thanks hexgrid and sancho2!