XScript Manual · Chapter 34

JSON Object — JSON document handling

The script keyword JSON provides JSON utilities. A single process can hold multiple JSON documents identified by name, and any document can be read/written via path notation (/root/items/0/name).

ConceptMeaning
jsonNameDocument identifier you choose ("recipe", "mes_response", …)
pathLocation inside the document — /key/key2/0/name (key for objects, index for arrays)
Result / errorEvery call sets an internal flag — GetResult / GetErrorMessage

Basic flow

// 1) Create an empty document
JSON.CreateJson("recipe");
 
// 2) Write values (intermediate paths are auto-created)
JSON.SetValue("recipe", "/title",       "AlignRecipe");
JSON.SetValue("recipe", "/version",     2);
JSON.SetValue("recipe", "/exposure_ms", 18.5);
JSON.SetValue("recipe", "/use_filter",  true);
 
// 3) Serialize
string text = JSON.ToJsonString("recipe");
Log(text);
// {"title":"AlignRecipe","version":2,"exposure_ms":18.5,"use_filter":true}
 
// 4) Save to disk
JSON.SaveJsonFile("recipe", "D:/Recipes/align.json");
 
// 5) Drop when done
JSON.RemoveJson("recipe");

Document lifecycle

// Load into memory
JSON.LoadJsonFile("mes",       "D:/Mes/inbound.json");
JSON.LoadJson    ("inline",    "{\"a\":1,\"b\":[2,3]}");
 
// Existence / clear / drop
if( JSON.Contains("mes") )      JSON.ClearJsonData("mes");
JSON.RemoveJson("mes");
JSON.RemoveAll();   // drop every registered document

Writing — SetValue (4 overloads)

JSON.SetValue("doc", "/name",     "Alice");      // string
JSON.SetValue("doc", "/age",      30);           // int
JSON.SetValue("doc", "/weight",   62.4);         // double
JSON.SetValue("doc", "/active",   true);         // bool
 
JSON.SetNullValue("doc", "/parent_id");          // explicit null

Missing paths are auto-created — no need to call AddObject first. To write into an array index, the array itself must already exist.


Reading — GetXxxValue

string n = JSON.GetStringValue("doc", "/name");                 // "Alice"
int    a = JSON.GetIntValue   ("doc", "/age");                  // 30
double w = JSON.GetDoubleValue("doc", "/weight",  -1.0);        // -1.0 if missing
bool   v = JSON.GetBoolValue  ("doc", "/active",  false);       // default fallback

The 3rd argument (default value) — returned when the key is missing or has a wrong type.

Trailing subtree

// Get all child keys/values from a node as one string
string sub = JSON.GetJsonStringByPath("doc", "/items/0");

Adding objects / arrays

// Add object node
JSON.AddObject("doc", "/",     "items");        // /items as empty object
JSON.AddObject("doc", "/items", "first");       // /items/first as empty object
 
// Add array node
JSON.AddArray ("doc", "/",     "tags");         // /tags as empty array
 
// Push into array (one object / one array)
JSON.AddObjectToArray("doc", "/items", 1);      // push 1 empty object
JSON.AddArrayToArray ("doc", "/tags",  1);      // push 1 empty array
 
// Direct SetValue on an index also works
JSON.SetValue("doc", "/tags/0", "auto");
JSON.SetValue("doc", "/tags/1", "vision");

Array maintenance

int n = JSON.GetItemCount("doc", "/tags");      // count
 
JSON.RemoveFromArray("doc", "/tags", 0);        // delete index 0
JSON.MoveArrayItem  ("doc", "/tags", 1, true);  // move index 1 up (swap with 0)
JSON.MoveArrayItem  ("doc", "/tags", 0, false); // move index 0 down
JSON.ClearArray     ("doc", "/tags");           // clear all

Result / error handling

Every call updates an internal result flag.

JSON.SetValue("doc", "/x/y/z", 1);
 
if( JSON.GetResult("doc") == false )
{
    LogError($"JSON SetValue failed : {JSON.GetErrorMessage("doc")}");
    JSON.ResetResult("doc");
}

Pattern — verify after a series of calls:

JSON.ResetResult("doc");
JSON.SetValue("doc", "/a", 1);
JSON.SetValue("doc", "/b/c", 2);
JSON.SetValue("doc", "/b/arr/0", "x");
if( JSON.GetResult("doc") == false )
{
    ShowMessage(EB_Ok, JSON.GetErrorMessage("doc"));
    return false;
}

Serialization / pretty-print

string compact = JSON.ToJsonString("doc");          // single line
string pretty  = JSON.FormatJson(compact);          // indented

FormatJson only transforms an input string — it doesn't touch any registered document.


Common patterns

Save / load recipe

FUNCTION SaveRecipe(string filePath)
{
    JSON.CreateJson("rec");
    JSON.SetValue("rec", "/exposure_ms", Data::Exposure);
    JSON.SetValue("rec", "/light_pct",   Data::Light);
    JSON.AddArray("rec", "/", "trims");
    for(i, 0, 9)
    {
        JSON.AddObjectToArray("rec", "/trims", 1);
        JSON.SetValue("rec", $"/trims/{i}/x", Data::TrimX[i]);
        JSON.SetValue("rec", $"/trims/{i}/y", Data::TrimY[i]);
    }
    JSON.SaveJsonFile("rec", filePath);
    JSON.RemoveJson("rec");
}
 
FUNCTION LoadRecipe(string filePath)
{
    if( JSON.LoadJsonFile("rec", filePath) == false )
    {
        ShowMessage(EB_Ok, $"Load failed : {JSON.GetErrorMessage("rec")}");
        return false;
    }
    Data::Exposure = JSON.GetDoubleValue("rec", "/exposure_ms", 0);
    Data::Light    = JSON.GetIntValue   ("rec", "/light_pct",   0);
 
    int n = JSON.GetItemCount("rec", "/trims");
    for(i, 0, n - 1)
    {
        Data::TrimX[i] = JSON.GetDoubleValue("rec", $"/trims/{i}/x", 0);
        Data::TrimY[i] = JSON.GetDoubleValue("rec", $"/trims/{i}/y", 0);
    }
    JSON.RemoveJson("rec");
    return true;
}

Parse MES response

JSON.LoadJson("resp", responseString);
 
if( JSON.GetBoolValue("resp", "/ok", false) == false )
{
    ShowError(EB_Reset, 1, JSON.GetStringValue("resp", "/message"));
    return false;
}
int lotSeq = JSON.GetIntValue("resp", "/data/lot_seq", 0);

Quick reference

GroupFunctions
LifecycleCreateJson · LoadJson · LoadJsonFile · SaveJsonFile · RemoveJson · RemoveAll · ClearJsonData · Contains
ResultGetResult · GetErrorMessage · ResetResult
WriteSetValue (string/int/double/bool) · SetNullValue
ReadGetStringValue · GetIntValue · GetDoubleValue · GetBoolValue · GetJsonStringByPath
TreeAddObject · AddArray
Array opsAddObjectToArray · AddArrayToArray · RemoveFromArray · ClearArray · GetItemCount · MoveArrayItem
SerializeToJsonString · FormatJson