JSON module for Argentum programming language allows to parse JSONs directly in application data structures, skipping the creation of JSON DOM. This takes two times less memory and reduces the time overheads by three-folds. The usual alternative to DOM parsers is streaming SAX parser, that requires application to have cumbersome state machine to handle data. Argentum JSON module doesn't use it either.
JSON Parsing in Argentum is simple and extremely effective.
For example, if we have such data structures:
class Polygon {
name = "";
points = Array(Point);
isActive = false;
}
class Point{
x = 0f;
y = 0f;
}
... and we want to read JSONs of this structure:
[
{
"active": false,
"name": "p1",
"points": [
{"x": 11, "y": 32},
{"y": 23, "x": 12},
{"x": -1, "y": 4}
]
},
{
"points": [
{"x": 10, "y": 0},
{"x": 0, "y": 10},
{"y": 0, "x": 0}
],
"active": true,
"name": "Corner"
}
]
... we can do it with this function:
using json { Parser }
fn readPolygonsFromJson(data str) Array(Polygon) {
Array(Polygon).{
json = Parser.init(data);
json.getArr\_.append(Polygon)-> json.getObj `f
f=="active" ? _.isActive := json.getBool(false) :
f=="name" ? _.name := json.getStr("") :
f=="points" ? json.getArr\_.points.append(Point)-> json.getObj `f (
f=="x" ? _.x := float(json.getNum(0.0)) :
f=="y" ? _.y := float(json.getNum(0.0)));
json.success() : log("parsing error {json.getErrorMessage()}{json.getErrorPos()?" at {_.offset}"}");
}
}
As you can see this function contains just:
- mapping JSON field names to Argentum class fields,
- data conversions/validation,
- creations objects of types we want
- populating collections we want the way you want
It also checks and handles all format errors. And it is all in just 12 lines of code.
Despite its size, this function handles all the edge cases:
- If input JSON has an unexpected field, this field is skipped.
- This code is tolerant to any order of fields in objects.
- If some needed field is absent from JSON, the it uses default values or calls handlers.
- If some field, root element or array item in the JSON is of an unexpected type, it handles this as well.
- Since all parsing is performed in plain Argentum code, we can easily add validating/transforming/versioning logic without inventing template-driven or string-encoded DSLs.
- This parser is extremely rigid and resilient, it validates its input against JSON standard, detects and reports all errors.
Let's call this function for completeness:
myPolygons = readPolygonsFromJson("
[{
"active": false,
"name": "p1",
"points": [ {"x": 11, "y": 32}, {"y": 23, "x": 12}, {"x": -1, "y": 4}]
},{
"points": [{"x": 10, "y": 0}, {"x": 0, "y": 10}, {"y": 0, "x": 0}],
"active": true,
"name": "Corner"
}]
")
Pretty high-level for a language that compiles to tiny standalone machine code executables and runs at the speed of C++?
Details are here https://aglang.org/json-module/
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.