Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | bqio |
["0.1", "simple", "true", "12"] # how convert to
[0.1, "simple", true, 12]
Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | bqio |
["0.1", "simple", "true", "12"] # how convert to
[0.1, "simple", true, 12]
Reply From: | jgodfrey |
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…
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?
bqio | 2020-06-23 03:51
Reply From: | rakkarage |
var _newTest := {
"data": {
"f": 0.1,
"s": "simple",
"b": true,
"i": 12
}
}
print(_newTest)
var json = to_json(_newTest)
print(json)
var obj = JSON.parse(json)
print(obj)
print(obj.data.b == true)
if you can fit your data into a Dictionary to_json and parse_json can convert all types to string and back
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.
bqio | 2020-06-23 03:42
Reply From: | bqio |
Here is my solution: