Clone
1
Builtin json parser (ajson)
zobnin edited this page 2022-08-29 12:51:57 +03:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

The AIO Launcher includes two modules for working with JSON. The first is json.lua, an external module that allows you to convert JSON into a Lua nested table and vice versa. In most cases, its use is preferable.

The second module is ajson, which allows you to extract individual values from JSON. Ajson module works well (and very fast) when you need to retrieve one or two values. It is especially good on very large JSON files.

AJSON

  • ajson:get_value(string, string) - gets the specified value from JSON; the first argument is a JSON string, the second is an instruction to get the value.

Unlike classic JSON parsers, this function is not intended for parsing, but for retrieving single values. For example, there is the following JSON:

{
  "type": "success",
  "value": {
    "id": 344,
    "joke": "Aliens DO indeed exist. They just know better than to visit a planet that Chuck Norris is on.",
    "categories": []
  }
}

We need to extract string "joke" from it. From the JSON text, you can see that this string is contained within the "value" object, and this object itself is inside the main JSON object. In other words, to retrieve the required string, we need to "open" the main JSON object, then "open" the "value" object and find the string "joke" in it. In code, it will look like this:

joke = ajson:get_value(result, "object object:value string:joke")

The full text of the script may look like this:

function on_alarm()
    http:get("http://api.icndb.com/jokes/random")
end

function on_network_result(result)
    local joke = ajson:get_value(result, "object object:value string:joke")
    aio:show_text(joke)
end

Another example:

{
  "attachments": [
    {
      "fallback": "Whats Forest Gumps Facebook password? 1forest1",
      "footer": "<https://icanhazdadjoke.com/j/7wciy59MJe|permalink> - <https://icanhazdadjoke.com|icanhazdadjoke.com>",
      "text": "Whats Forest Gumps Facebook password? 1forest1"
    }
  ],
  "response_type": "in_channel",
  "username": "icanhazdadjoke"
}

To extract "text" value we need to use this code:

joke = ajson:get_value(result, "object array:attachments object:0 string:text")

Please note that the last element of the line should always be an instruction for extracting primitive data types:

  • string:name
  • int:name
  • double:name
  • boolean:name