XScript 手册 · Chapter 34

JSON 对象 — JSON 文档处理

脚本中以关键字 JSON 访问的 JSON 工具。一个进程中可以按名称同时管理多个 JSON 文档,并通过 path 表示法(/root/items/0/name)自由读写。

概念说明
jsonName用户自定义的文档标识("recipe""mes_response")
path文档内部位置 — /key/key2/0/name(对象用键、数组用索引)
结果 / 错误每次调用都更新内部标志 — GetResult / GetErrorMessage

基本流程

// 1) 创建空文档
JSON.CreateJson("recipe");
 
// 2) 写入值(中间路径自动创建)
JSON.SetValue("recipe", "/title",       "AlignRecipe");
JSON.SetValue("recipe", "/version",     2);
JSON.SetValue("recipe", "/exposure_ms", 18.5);
JSON.SetValue("recipe", "/use_filter",  true);
 
// 3) 序列化
string text = JSON.ToJsonString("recipe");
Log(text);
// {"title":"AlignRecipe","version":2,"exposure_ms":18.5,"use_filter":true}
 
// 4) 保存到磁盘
JSON.SaveJsonFile("recipe", "D:/Recipes/align.json");
 
// 5) 不再需要时移除
JSON.RemoveJson("recipe");

文档生命周期

JSON.LoadJsonFile("mes",       "D:/Mes/inbound.json");
JSON.LoadJson    ("inline",    "{\"a\":1,\"b\":[2,3]}");
 
if( JSON.Contains("mes") )      JSON.ClearJsonData("mes");
JSON.RemoveJson("mes");
JSON.RemoveAll();   // 移除所有已注册文档

写入 — SetValue(4 个重载)

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");          // 显式 null

不存在的 path 会自动创建 — 无需先调 AddObject。但要写入数组索引时,数组本身必须已存在


读取 — 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
bool   v = JSON.GetBoolValue  ("doc", "/active",  false);       // 默认值兜底

第 3 参数(默认值)— 键缺失或类型不符时返回该值。

子树字符串

// 从某节点开始的所有子键值,作为一个字符串
string sub = JSON.GetJsonStringByPath("doc", "/items/0");

添加对象 / 数组

JSON.AddObject("doc", "/",     "items");        // /items 为空对象
JSON.AddObject("doc", "/items", "first");       // /items/first 为空对象
 
JSON.AddArray ("doc", "/",     "tags");         // /tags 为空数组
 
JSON.AddObjectToArray("doc", "/items", 1);      // push 1 个空对象
JSON.AddArrayToArray ("doc", "/tags",  1);      // push 1 个空数组
 
JSON.SetValue("doc", "/tags/0", "auto");
JSON.SetValue("doc", "/tags/1", "vision");

数组操作

int n = JSON.GetItemCount("doc", "/tags");
 
JSON.RemoveFromArray("doc", "/tags", 0);
JSON.MoveArrayItem  ("doc", "/tags", 1, true);  // index 1 → 上移
JSON.MoveArrayItem  ("doc", "/tags", 0, false); // index 0 → 下移
JSON.ClearArray     ("doc", "/tags");

结果 / 错误处理

每次调用都会更新内部结果标志。

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

多次调用后统一校验:

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;
}

序列化 / 美化

string compact = JSON.ToJsonString("doc");          // 单行
string pretty  = JSON.FormatJson(compact);          // 缩进

FormatJson 仅转换输入字符串 — 不影响已注册文档。


常用模式

保存 / 读取配方

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;
}

解析 MES 响应

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);

函数一览

分类函数
生命周期CreateJson · LoadJson · LoadJsonFile · SaveJsonFile · RemoveJson · RemoveAll · ClearJsonData · Contains
结果GetResult · GetErrorMessage · ResetResult
写入SetValue(string/int/double/bool)· SetNullValue
读取GetStringValue · GetIntValue · GetDoubleValue · GetBoolValue · GetJsonStringByPath
树构建AddObject · AddArray
数组AddObjectToArray · AddArrayToArray · RemoveFromArray · ClearArray · GetItemCount · MoveArrayItem
序列化ToJsonString · FormatJson