TinyMUX

JSON

Topics

Overview

TinyMUX 2.14 provides a comprehensive set of functions for constructing, querying, modifying, and validating JSON data. JSON support is useful for GMCP communication with clients, structured data storage in attributes, and integration with external APIs.

Constructing JSON

json()

json(<type>, <value1>[, <value2>, ...])

Constructs a JSON value of the specified type. Supported types:

  • stringjson(string, hello) produces "hello"
  • numberjson(number, 42) produces 42
  • booleanjson(boolean, 1) produces true; json(boolean, 0) produces false
  • nulljson(null) produces null
  • arrayjson(array, "a", "b", "c") produces ["a","b","c"]
  • objectjson(object, key1, "val1", key2, "val2") produces {"key1":"val1","key2":"val2"}

Querying JSON

json_query()

json_query(<json>, <operation>[, <path>])

Queries a JSON document. Operations include:

  • type – Returns the JSON type of the value (string, number, boolean, null, array, object).
  • size – Returns the number of elements in an array or keys in an object.
  • exists – Returns 1 if the specified path exists, 0 otherwise.
  • get – Returns the value at the specified path.
  • keys – Returns the keys of an object.
  • values – Returns the values of an object or elements of an array.

Paths use SQLite JSON path syntax: $.key for object members and $[0] for array indices.

Modifying JSON

json_mod()

json_mod(<json>, <operation>, <path>, <value>)

Modifies a JSON document and returns the result. Operations include:

  • set – Sets the value at <path>, creating or replacing as needed.
  • insert – Inserts <value> at <path> only if the path does not already exist.
  • replace – Replaces the value at <path> only if it already exists.
  • remove – Removes the value at <path>.
  • patch – Applies a JSON merge patch to the document.

Validating JSON

isjson()

isjson(<string>)

Returns 1 if <string> is valid JSON, 0 otherwise.

Examples

Construct and query a JSON object:

> say json(object, name, "Guard", hp, json(number, 100))
You say "{"name":"Guard","hp":100}"

> say json_query({"name":"Guard","hp":100}, get, $.name)
You say "Guard"

> say json_query({"name":"Guard","hp":100}, type)
You say "object"

Modify a JSON document:

> say json_mod({"hp":100}, set, $.hp, json(number, 75))
You say "{"hp":75}"

> say json_mod({"a":1}, insert, $.b, json(number, 2))
You say "{"a":1,"b":2}"

> say json_mod({"a":1,"b":2}, remove, $.b)
You say "{"a":1}"

Build a JSON array and query its size:

> say json(array, "red", "green", "blue")
You say "["red","green","blue"]"

> say json_query(["red","green","blue"], size)
You say "3"

Validate JSON:

> say isjson({"valid":true})
You say "1"

> say isjson({broken)
You say "0"

json(), json_query(), json_mod(), isjson(), GMCP Protocol.