HaxeFoundation / haxe.org-comments

Repository to collect comments of our haxe.org websites
2 stars 2 forks source link

[haxe.org/manual] Parsing JSON #22

Open utterances-bot opened 5 years ago

utterances-bot commented 5 years ago

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

daverave1212 commented 5 years ago

How do you iterate through the keys of a parsed JSON object?

Aurel300 commented 5 years ago

@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);
}
KaiSD commented 5 years ago

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

Gama11 commented 5 years ago

@KaiSD I'd recommend using a library like json2object or tink_json for that.

markknol commented 5 years ago

@KaiSD thats not an actual map, its just a plain object. You could iterate that using Reflect.

for (k in Reflect.fields(o.map)) {
  trace(k, Reflect.field(o.map, k));
}

.. or type it as haxe.DynamicAccess like @Aurel300 just describe above.