Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[haxe.org/manual] Parsing JSON #22

Open
utterances-bot opened this issue Jul 21, 2019 · 5 comments
Open

[haxe.org/manual] Parsing JSON #22

utterances-bot opened this issue Jul 21, 2019 · 5 comments

Comments

@utterances-bot
Copy link

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

Copy link

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

@Aurel300
Copy link
Member

@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);
}

Copy link

KaiSD commented Sep 30, 2019

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
Copy link
Member

Gama11 commented Sep 30, 2019

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

@markknol
Copy link
Member

markknol commented Oct 1, 2019

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants