Open utterances-bot opened 5 years ago
How do you iterate through the keys of a parsed JSON object?
@daverave1212 The return type of haxe.Json.parse
is Dynamic
. To iterate through the keys, you are looking for a Map
-like interface to Dynamic
, which is possible with haxe.DynamicAccess
. It is an abstract over Dynamic
, so you can simply assign the return value of parse
to a variable with type DynamicAccess
:
var myObj:haxe.DynamicAccess<Dynamic> = haxe.Json.parse('{"foo": true, "bar": 2}');
for (key in myObj.keys()) trace(key, myObj.get(key));
// or using Haxe 4 syntax:
for (key => value in myObj) trace(key, value);
If you are sure that all the values in a given object will have the same type, you can use DynamicAccess
with the given type as type parameter:
var myObj:haxe.DynamicAccess<Int> = haxe.Json.parse('{"foo": 1, "bar": 2}');
for (key => value in myObj) {
// here, `value` is `Int`, rather than `Dynamic` as in the previous example
trace(key, value);
}
Is there a way to parse maps from JSON into actual maps?
I can iterate through an array or even push into an array. But if I try to iterate through a map, I'm getting a TypeError.
An example: https://try.haxe.org/#08f25
@KaiSD I'd recommend using a library like json2object or tink_json for that.
Parsing JSON - Haxe - The Cross-platform Toolkit
Haxe is an open source toolkit based on a modern, high level, strictly typed programming language.
https://haxe.org/manual/std-Json-parsing.html