0 votes
["0.1", "simple", "true", "12"] # how convert to
[0.1, "simple", true, 12]
in Engine by (19 points)

4 Answers

+1 vote
Best answer

In gdscript, an Array is a generic container that can hold varying data types (strings, ints, floats, ...). So, there's really no need to convert the array itself. Really, you're talking about converting the data type of some the array's individual elements.

You can convert a string rep of a number ("0.1") to an actual number in several ways, including:

var some_int = int("12")
var some_float = float("0.1")

... or ...

var some_int2 = "12" as int
var some_float2 = "0.1" as float

So, really, it's a matter of iterating through the array and converting the "numeric strings" to actual numbers, and updating the values as necessary.

If you know which elements need to be converted, it should be really easy. Otherwise, if you just want to convert everything to a number that can be converted to a number, you'll have to somehow test each value or appropriately trap errors that could happen during the conversion process of non-convertible values.

I'd think the above should be enough to get you started. If that's not the case, let us know where you're having trouble...

by (10,914 points)
selected by

How can I check them for errors? float (), bool (), int () in case of failure return 0. But after all, there can also be "0". Is there really no way to catch a error?

–1 vote
var _newTest := {
    "data": {
        "f": 0.1,
        "s": "simple",
        "b": true,
        "i": 12
var json = to_json(_newTest)
var obj = JSON.parse(json)
print(obj.data.b == true)

if you can fit your data into a Dictionary tojson and parsejson can convert all types to string and back

by (1,665 points)
edited by

The problem is that the original data comes as an array of strings. And if you convert the array of strings to JSON, then it will remain an array of strings, and will not convert to the desired type.

0 votes

Here is my solution:

enter image description here

by (19 points)
0 votes

you can use 'str2var' if string is formatted right
this videos explains some issues and alternatives

by (1,665 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.