COMMUNITY

JSON Attributes with numbers as name


(Nicolas Korbel) #1

Hi there,
i try to write a small little reporting app for our projectmanagment tool at work using haxe.

Now I’ve got a problem:
The REST API of the pm tool returns some json data. Everything worked fine.
In a special case I get some dynamical Json like:

{ "attributes_values": { "1": "240 min" },
    "user_story": 1,
    "version": 2
}

or

{ "attributes_values": {"122": "tgu", "97": "1,5", "98": "2017-11-10"},
 "version": 5,
 "user_story": 756
}

Anyone an idea how I can get the values of the “attribute_values”? They are dynamically. In the first example I have to read the value of “1”(=“240 min”) and in the second example I have to read the value of “122”(=tgu)

I tried a lot: Using maps, parsing the value of “attribute_values” into a new json-object and read it with object.122 and many more… but nothing worked for me.

I hope someone can help me.

Thanks a lot.


(Aleksandr Kuzmenko) #2
import haxe.DynamicAccess;
import haxe.Json;

class Test {
    static function main() {
        var obj:DynamicAccess<String> = Json.parse('{ "1": "240 min" }');
        trace(obj["1"]);
    }
}

https://try.haxe.org/#be78e


(Jens Fischer) #3

Or you can use the json2object library if you want to avoid Dynamic. It supports deserialization into a Haxe Map, among other things.

class Main {
	public static function main() {
		var parser = new json2object.JsonParser<Data>();
		var obj = parser.fromJson('{ "1": "240 min" }', "data.json");
		trace(obj[1]);
	}
}

typedef Data = Map<Int, String>;