Close

Argentum apps can parse JSONs

A project log for Argentum programming language

It automatically prevents all memory leaks. It doesn't use GC, so no pauses. It's compiled to machine code. It's crazy safe and fast.

andrey-kalmatskiyAndrey Kalmatskiy 12/02/2024 at 20:360 Comments

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:

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:

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