XScript Manual · Chapter 34

JSON Object — Building and Reading JSON Documents

JSON is a collection of functions for building and reading JSON documents. Each document is kept in memory under a name (jsonName), and a location inside a document is addressed with a path (path).

  • Documents are stored by name in one place shared by all modules. Use names that do not clash with other modules, and remove documents you no longer need with RemoveJson. All documents are removed when a project is opened.
  • A failed call leaves an error flag on that document. Check it with GetResult and read the details with GetErrorMessage.

Path notation

JSON paths use dots (.) and [index].

NotationMeaningExample
keyKey of the root objecttitle
key.keyDots join the keys of nested objectscamera.light.level
key[n]Element n of an array (from 0)trims[2].x
"" (empty string)Document root — used with AddObject / AddArray to add to the rootJSON.AddArray("doc", "", "tags")
  • Do not start a path with / or separate parts with / or :. "/title" becomes a key literally named /title, and "items/0" or "items:0" are also taken as literal key names.
  • When writing (SetValue, SetNullValue, AddArray), missing objects and arrays along the path are created. Writing trims[2].x for the first time creates the trims array and fills positions 0 and 1 with empty objects {}.

Example

Building a document · saving it to a file

xscript
JSON.CreateJson("recipe");                               // empty document {}
JSON.SetValue("recipe", "title", "AlignRecipe");
JSON.SetValue("recipe", "version", 2);
JSON.SetValue("recipe", "exposure_ms", 18.5);
JSON.SetValue("recipe", "use_filter", true);
JSON.SetValue("recipe", "camera.light.level", 70);       // creates the camera and light objects
 
Log(JSON.ToJsonString("recipe"));                        // whole document ( indented JSON string )
JSON.SaveJsonFile("recipe", "D:\\Recipes\\align.json");
JSON.RemoveJson("recipe");                               // remove the document when done

Saved file:

json
{
  "title": "AlignRecipe",
  "version": 2,
  "exposure_ms": 18.5,
  "use_filter": true,
  "camera": {
    "light": {
      "level": 70
    }
  }
}

Arrays — saving and reading back

xscript
array TrimX[10] = {0.0};   // trim value X
array TrimY[10] = {0.0};   // trim value Y
 
FUNCTION bool SaveTrims(string filePath)
{
   JSON.CreateJson("trim");
   for(i, 0, 9)
   {
      JSON.SetValue("trim", $"trims[{i}].x", TrimX[i]);   // creates the trims array and its element objects
      JSON.SetValue("trim", $"trims[{i}].y", TrimY[i]);
   }
   bool ok = JSON.SaveJsonFile("trim", filePath);
   JSON.RemoveJson("trim");
   return ok;
}
 
FUNCTION bool LoadTrims(string filePath)
{
   if( SYS.ExistsFile(filePath) == false )
   {
      LogError("trim file not found : {0}", filePath);
      return false;
   }
   JSON.LoadJsonFile("trim", filePath);
   if( JSON.GetResult("trim") == false )                  // false if the file content is not JSON
   {
      LogError("trim file error : {0}", JSON.GetErrorMessage("trim"));
      JSON.RemoveJson("trim");
      return false;
   }
   int n = JSON.GetItemCount("trim", "trims");            // -1 if there is no array → the loop below does not run
   if( n > 10 )
   {
      n = 10;
   }
   for(i, 0, n - 1)
   {
      TrimX[i] = JSON.GetDoubleValue("trim", $"trims[{i}].x", 0.0);
      TrimY[i] = JSON.GetDoubleValue("trim", $"trims[{i}].y", 0.0);
   }
   JSON.RemoveJson("trim");
   return true;
}

LoadJsonFile returns true even when the file content is not JSON, so check the result with GetResult. Calling it with a new name for a file that does not exist raises a runtime error, so check with SYS.ExistsFile first.

Reading a server response

xscript
int    LotSeq  = 0;    // lot sequence number from the server
string LotName = "";   // name of the first item
 
FUNCTION bool RequestLot(string url)
{
   string resp = SYS.SendHttpGet(url);                   // "[HTTP-ERROR]" on failure
   if( JSON.LoadJson("lot", resp) == false )              // false if it is not JSON
   {
      LogError("lot response error : {0}", resp);
      JSON.RemoveJson("lot");                            // an empty document remains even on failure, so remove it
      return false;
   }
   if( JSON.GetBoolValue("lot", "ok", false) == false )
   {
      LogError("lot rejected : {0}", JSON.GetStringValue("lot", "message"));
      JSON.RemoveJson("lot");
      return false;
   }
   LotSeq  = JSON.GetIntValue("lot", "data.lot_seq", 0);
   LotName = JSON.GetStringValue("lot", "data.items[0].name", "");
   JSON.RemoveJson("lot");
   return true;
}

Sample response:

json
{ "ok": true, "message": "", "data": { "lot_seq": 7, "items": [ { "name": "A01" } ] } }

Editing an array and checking for errors

xscript
JSON.CreateJson("doc");
JSON.AddArray("doc", "", "tags");                    // empty array tags at the root
JSON.AddObjectToArray("doc", "tags", 2);             // append 2 empty objects
JSON.SetValue("doc", "tags[0].name", "auto");
JSON.SetValue("doc", "tags[1].name", "vision");
JSON.MoveArrayItem("doc", "tags", 1, true);          // swap element 1 with the one before → vision, auto
JSON.RemoveFromArray("doc", "tags", 5);              // no such index → only an error flag is left
if( JSON.GetResult("doc") == false )
{
   LogError("json edit failed : {0}", JSON.GetErrorMessage("doc"));
   JSON.ResetResult("doc");                         // clear the error flag with ResetResult
}

Methods

Create · load · save

MethodDescription
bool CreateJson(string jsonName)Creates an empty document ({}) and returns true. If the name already exists, its content is cleared and false is returned (the error flag is kept).
bool LoadJson(string jsonName, string jsonString)Reads a JSON string (object or array) into a document, replacing any document of the same name. On a syntax error it returns false — the name is left as an empty document with an error flag. On success the document starts with no error flag.
bool LoadJsonFile(string jsonName, string filePath)Reads a file and processes it like LoadJson. It returns true even if the file content has a JSON syntax error, so check GetResult. If the file cannot be read it returns false with an error flag (the previous content is kept); with a new name it raises a runtime error.
bool SaveJsonFile(string jsonName, string filePath)Saves the document as an indented UTF-8 file. Folders are not created. If saving fails it returns false with an error flag. An unknown document name raises a runtime error.
string ToJsonString(string jsonName)Returns the whole document as a JSON string with indentation and line breaks. Returns "" for an unknown name.
string FormatJson(string jsonString)Returns the JSON string reformatted with indentation. Registered documents are not touched; if the input is not JSON, it is returned unchanged.

Document management

MethodDescription
bool Contains(string jsonName)true if a document with that name exists.
bool ClearJsonData(string jsonName)Removes all content of the document (the document remains). false for an unknown name.
bool RemoveJson(string jsonName)Removes the document. false for an unknown name.
void RemoveAll()Removes every document, including documents used by other modules.

Checking results

MethodDescription
bool GetResult(string jsonName)true if the document exists and has no error flag.
string GetErrorMessage(string jsonName)Returns the last error message. "" if there is no error or the name is unknown.
void ResetResult(string jsonName)Clears the error flag and message. The error flag is cleared only by this function or by a successful LoadJson / LoadJsonFile.

Writing values

The SetValue overload that matches the type of the value (string, integer, real, bool) is used. Missing objects and arrays along the path are created, and so is the document if it does not exist. Any value or object already at that location is replaced.

MethodDescription
void SetValue(string jsonName, string path, string value)Writes a string value.
void SetValue(string jsonName, string path, int value)Writes an integer value.
void SetValue(string jsonName, string path, double value)Writes a real value. Whole numbers are also written with a decimal point, such as 2.0.
void SetValue(string jsonName, string path, bool value)Writes true / false.
void SetNullValue(string jsonName, string path)Writes null.

Reading values

defaultValue is returned when the path does not exist or the value is null, and it can be omitted. A missing path does not set the error flag. If a value exists but cannot be converted to the requested type (for example, reading "abc" with GetIntValue or an object with GetStringValue), a runtime error is raised.

MethodDescription
string GetStringValue(string jsonName, string path, string defaultValue="")Reads as a string. Number and bool values are converted to strings.
int GetIntValue(string jsonName, string path, int defaultValue=0)Reads as an integer.
double GetDoubleValue(string jsonName, string path, double defaultValue=0)Reads as a real number.
bool GetBoolValue(string jsonName, string path, bool defaultValue=false)Reads as a bool.
string GetJsonStringByPath(string jsonName, string path)Returns the value at that location as an indented JSON string. Use it to take out a whole object or array (a string value includes its quotes). Returns "" if the path does not exist.

Adding objects · arrays

These functions need an existing document. An unknown document name raises a runtime error.

MethodDescription
void AddObject(string jsonName, string path, string objectName)Adds an empty object under the key objectName in the object at path. An existing key is replaced with an empty object. If path does not exist, nothing is created and only an error flag is set. The root is "".
void AddArray(string jsonName, string path, string arrayName)Adds an empty array under the key arrayName in the object at path. An existing key is replaced with an empty array. A missing path is created.
void AddObjectToArray(string jsonName, string arrayPath, int numOfAdd=1)Appends numOfAdd empty objects to the end of the array. Sets an error flag if it is not an array.
void AddArrayToArray(string jsonName, string arrayPath, int numOfAdd=1)Appends numOfAdd empty arrays to the end of the array. Sets an error flag if it is not an array.

Working with arrays

MethodDescription
int GetItemCount(string jsonName, string path)Returns the number of elements in the array. -1 if it is not an array or does not exist.
void RemoveFromArray(string jsonName, string arrayPath, int index)Removes element index. An out-of-range index sets an error flag. An unknown document name raises a runtime error.
void ClearArray(string jsonName, string arrayPath)Removes all elements of the array. Sets an error flag if it is not an array. An unknown document name raises a runtime error.
bool MoveArrayItem(string jsonName, string arrayPath, int index, bool moveUp)Swaps element index with the element before it (moveUp = true) or after it (false). Moving the first element up, the last element down, or an out-of-range index returns false with an error flag.

Notes

When the document name does not exist

FunctionBehavior
Value-reading functions · GetItemCount · ToJsonStringReturn the default value · -1 · "".
SetValue · SetNullValueCreate a new document with that name and write to it.
GetResult · GetErrorMessageReturn false · "".
ClearJsonData · RemoveJson · MoveArrayItemReturn false.
AddObject · AddArray · AddObjectToArray · AddArrayToArray · RemoveFromArray · ClearArray · SaveJsonFile · LoadJsonFile (when the file cannot be read)Runtime error — execution stops at that point.

Other notes

  • ToJsonString and SaveJsonFile always write the indented format with line breaks. There is no function that produces a single-line string. SaveJsonFile writes UTF-8 without a BOM.
  • long values are stored as real numbers (double), so large values such as ticks may lose their last digits. Store such values as strings (for example with DATE.ConvertDateTimeString — DATE).
  • SaveJsonFile does not create folders. Call SYS.CreateDirectory first if needed (SYS).
  • Arguments with default values (defaultValue, numOfAdd) can be omitted. Function names are case-sensitive, and a call to an unknown name or with the wrong number of arguments is reported as a build error (Compile diagnostics).
Subscribe