Thursday, September 19, 2019

Parse JSON in pure X++

I decided to write a JSON parser in X++, because I couldn't find a useful implementation elsewhere. I wanted to avoid using external dll-based libraries.

It can handle strings, numbers (int and real), null-values and booleans. All kinds of linebreaks will be ignored.

It can be used like this:
str json = '{"foo": [1, 2, {"bar": 2}, {"bar": 3}]}';

AhkJSONObject ele = AhkJSONParser::parse(json);
AhkJSONArray arr = ele.get("foo");
AhkJSONObject obj = arr.get(3);
;

info('Demo 1: bar=' + obj.get("bar").strVal());
info('Demo 2: bar=' + AhkJSONParser::parse(json).getObjVal('foo').getArrayItem(3).getObjVal('bar').strVal());
info('Demo 3: bar=' + AhkJSONParser::parse(json).getObjVal('foo').getArrayItemWhere('bar', '3').getObjVal('bar').strVal());


Which will output:
Demo 1: bar=2
Demo 2: bar=2
Demo 3: bar=3

Please note the selection in demo 3, which makes it easy to select the correct array item. The project can be downloaded from the following url and is exported from AX 2009:
https://oc.ahkpro.dk/index.php/s/Q52BQ56zyrp2co8

The implementation is largely based on this python project:
https://github.com/eatonphil/pj/tree/master/pj

2020-01-20 update: I have updated the project with a few bugfixes, which should solve the two issues reported in comments.
2020-03-30 update: I have updated the project with a fix for parsing arrays as the outer type.