I'm a very new to coding and generally work with a drag and drop editor that is based on Haxe (Stencyl) as a hobby.
I have a JSON file that I would like to convert into a nested map (dictionary). I have tried using the JSON parsing function but it returns an anonymous (dynamic) structure.
How can I either convert the JSON file into a map or convert the Anonymous structure into a map?
Sample of the JSON:
{
"apple": {
"value": 10,
"health": 15,
"tags": [
"fruit",
"fiber",
"sweet"
]
},
"lemon": {
"value": 5,
"health": 10,
"tags": [
"fruit",
"citrus",
"sour"
]
},
"ham": {
"value": 50,
"health": 50,
"tags": [
"salty",
"meat"
]
}
}
Another option would be to use the json2object library, which natively supports Map<String, T>
:
import sys.io.File;
import json2object.JsonParser;
class Main {
public static function main() {
var parser = new JsonParser<Data>();
var source = File.getContent("data.json");
var data = parser.fromJson(source, "data.json");
trace(data["apple"].value); // 10
}
}
typedef Data = Map<String, {
var value:Int;
var health:Int;
var tags:Array<String>;
}>
This approach avoids both reflection and Dynamic
, which are usually considered bad practice.
You could create Map and fill it via Reflect api:
var parse = haxe.Json.parse(s);
var map:Map<String, StructData> = new Map();
for(field in Reflect.fields(parse))
{
map.set(field, Reflect.field(parse, field));
}
typedef StructData = {
var value:Int;
var health:Int;
var tags:Array<String>;
}
https://try.haxe.org/#DFa77
Take a look at the DynamicAccess
abstract here.
Given your sample I've made a quick example here:
import haxe.DynamicAccess;
typedef Food = {
var value:Int;
var health:Int;
var tags:Array<String>;
}
class Test {
static function main() {
var json = {
"apple": {
"value": 10,
"health": 15,
"tags": [
"fruit",
"fiber",
"sweet"
]
},
"lemon": {
"value": 5,
"health": 10,
"tags": [
"fruit",
"citrus",
"sour"
]
},
"ham": {
"value": 50,
"health": 50,
"tags": [
"salty",
"meat"
]
}
};
var foodMap:DynamicAccess<Food> = json;
// Get a single entry
var apple = foodMap.get("apple");
trace(apple.tags.join(", "));
// Loop through names
for (foodName in foodMap.keys()) {
trace(foodName);
trace(foodMap.get(foodName).value);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With