From Clomosy Docs

No edit summary
No edit summary
Line 30: Line 30:
<div style="margin-bottom: 20px;">
<div style="margin-bottom: 20px;">
{| class="infobox" style="width: 100%; border: 1px solid #28a745; background-color: #d4edda; border-radius: 5px; padding: 15px; border-collapse: separate;"
{| class="infobox" style="width: 100%; border: 1px solid #28a745; background-color: #d4edda; border-radius: 5px; padding: 15px; border-collapse: separate;"
| style="font-weight: bold; color: #28a745; padding-bottom: 5px;" | Important: Type-Safe JSON Values
| style="font-weight: bold; color: #28a745; padding-bottom: 5px;" | Dont Forget!
|-
|-
| TCLJSONValue provides class functions like '''Str''', '''Int''', '''Bool''', '''Num''', '''DT''', and '''Null''' to safely create JSON values without manual conversion.
| When working with nested objects or arrays, always free created JSON instances ('''Obj.Free;''', '''Arr.Free;''') after use to prevent memory leaks.
 
 
Also, ensure all JSON strings are '''UTF-8''' encoded before parsing to avoid character mismatches during validation.
|}
|}
</div>
</div>
Line 42: Line 45:
! style="background-color: #c3d7e0"| Definition
! style="background-color: #c3d7e0"| Definition
|-
|-
| '''TCLJSONObject''' || obj : TCLJSONObject; || Creates a variable for JSON object.
| '''ParseToJSONObject''' || obj = TCLJSON.ParseToJSONObject(jsonStr); || Parses a JSON string into a TCLJSONObject.
|-
| '''TCLJSONArray''' || arr : TCLJSONArray; || Creates a variable for JSON array.
|-
| '''AddPair''' || obj.AddPair('key', TCLJSONValue.Str('value')); || Adds a key-value pair to JSON object.
|-
|-
| '''AddObject''' || obj.AddObject('child', ChildObj); || Adds a nested JSON object.
| '''ParseObjectToString''' || jsonStr = TCLJSON.ParseObjectToString(obj); || Converts a TCLJSONObject to a JSON string.
|-
|-
| '''AddArray''' || obj.AddArray('letters', Arr); || Adds a JSON array inside object.
| '''ParseToJSONArray''' || arr = TCLJSON.ParseToJSONArray(jsonStr); || Parses a JSON string into a TCLJSONArray.
|-
|-
| '''Merge''' || obj.Merge(ExtraObj); || Merges another object into current.
| '''ParseArrayToString''' || jsonStr = TCLJSON.ParseArrayToString(arr); || Converts a TCLJSONArray to a JSON string.
|-
|-
| '''GetValueByPath''' || val = obj.GetValueByPath('level1.level2'); || Retrieves a value from nested path.
| '''LoadObjectFromFile''' || obj = TCLJSON.LoadObjectFromFile('data.json'); || Loads a JSON object from a file.
|-
|-
| '''ToJSONString''' || obj.ToJSONString; || Converts object/array to JSON string.
| '''SaveObjectToFile''' || TCLJSON.SaveObjectToFile(obj, 'data.json'); || Saves a TCLJSONObject to a file.
|-
|-
| '''IsValidJSON''' || TCLJSON.IsValidJSON(str); || Checks if string is valid JSON.
| '''IsValidJSON''' || valid = TCLJSON.IsValidJSON(jsonStr); || Checks whether a string is valid JSON.
|-
| '''SaveObjectToFile''' || TCLJSON.SaveObjectToFile(obj, 'file.json'); || Saves JSON object to file.
|}
|}
</div>
</div>




Line 69: Line 67:
var
var
   MyForm: TClForm;
   MyForm: TClForm;
   NameEdt, AgeEdt: TClProEdit;
   LoadBtn, SaveBtn, ParseBtn: TClProButton;
   ActiveChk: TClCheckBox;
  InputMemo, OutputMemo: TClMemo;
   ShowBtn: TClProButton;
   Obj: TCLJSONObject;
   ResultMemo: TClMemo;
   Arr: TCLJSONArray;
  JsonStr: string;
   Valid: Boolean;


void GenerateJSON
void LoadJSONFromFile
var
  Obj, Child, Extra: TCLJSONObject;
  Arr: TCLJSONArray;
  Val: TCLJSONValue;
{
{
   try
   Obj = TCLJSON.LoadObjectFromFile('data.json');
    // Main JSON object
  OutputMemo.Lines.Text = Obj.ToJSONString;
    Obj = TCLJSONObject.Create;
}
    try
      Obj.AddPair('name', TCLJSONValue.Str(NameEdt.Text));
      Obj.AddPair('age', TCLJSONValue.Int(StrToInt(AgeEdt.Text)));
      Obj.AddPair('active', TCLJSONValue.Bool(ActiveChk.isChecked));


      // Nested object
void SaveJSONToFile
      Child = TCLJSONObject.Create;
{
      Child.AddPair('ChildLevel', TCLJSONValue.Str('This is a deep value'));
  if Obj <> nil
      Obj.AddObject('ParentLevel', Child);
  {
    TCLJSON.SaveObjectToFile(Obj, 'output.json');
    ShowMessage('JSON saved to output.json');
  }
  else
    ShowMessage('No JSON object to save.');
}


      // Array
void ParseJSON
      Arr = TCLJSONArray.Create;
{
      Arr.AddValue(TCLJSONValue.Str('X'));
  try
      Arr.AddValue(TCLJSONValue.Str('Y'));
    JsonStr = InputMemo.Text;
      Arr.AddValue(TCLJSONValue.Str('Z'));
    Valid = TCLJSON.IsValidJSON(JsonStr);
      Obj.AddArray('letters', Arr);


      // Merge object
    if not Valid
      Extra = TCLJSONObject.Create;
    {
       Extra.AddPair('status', TCLJSONValue.Str('ok'));
       ShowMessage('Invalid JSON format!');
       Obj.Merge(Extra);
       exit;
    }


      // Deep value access (Optional)
    // Parse string to object
      Val = Obj.GetValueByPath('ParentLevel.ChildLevel');
    Obj = TCLJSON.ParseToJSONObject(JsonStr);
    ShowMessage('Parsed Object Key Count: ' + IntToStr(Obj.Count));


      // Add JSON to Memo
    // Convert object back to string
      ResultMemo.Lines.Text = Obj.ToJSONString;
    JsonStr = TCLJSON.ParseObjectToString(Obj);
    OutputMemo.Lines.Text = JsonStr;


      // Deep value shown (Optional)
    // Create sample array and show conversion
      ShowMessage('Deep value: ' + Val.AsString);
    Arr = TCLJSONArray.Create;
    Arr.AddValue(TCLJSONValue.Str('Item1'));
    Arr.AddValue(TCLJSONValue.Str('Item2'));
    OutputMemo.Lines.Add('');
    OutputMemo.Lines.Add('Array JSON:');
    OutputMemo.Lines.Add(TCLJSON.ParseArrayToString(Arr));


    except
      ShowMessage('Error: ' + LastExceptionMessage);
    }
   except
   except
     ShowMessage('Unexpected Error: ' + LastExceptionMessage);
     ShowMessage('Error: ' + LastExceptionMessage);
   }
   }
}
}
Line 125: Line 127:
   MyForm = TClForm.Create(Self);
   MyForm = TClForm.Create(Self);


   NameEdt = MyForm.AddNewProEdit(MyForm,'NameEdt','Name');
   InputMemo = MyForm.AddNewMemo(MyForm, 'InputMemo', 'Enter JSON Text');
   NameEdt.Align = alTop;
   InputMemo.Align = alTop;
   NameEdt.Height = 35;
   InputMemo.Height = 150;
  NameEdt.Margins.Left = 25;
  NameEdt.Margins.Bottom = 25;
  NameEdt.Margins.Right = 25;


   AgeEdt = MyForm.AddNewProEdit(MyForm,'AgeEdt','Age');
   OutputMemo = MyForm.AddNewMemo(MyForm, 'OutputMemo', 'Output');
   AgeEdt.Align = alTop;
   OutputMemo.Align = alClient;
  AgeEdt.Height = 35;
  AgeEdt.Margins.Left = 25;
  AgeEdt.Margins.Bottom = 25;
  AgeEdt.Margins.Right = 25;


   ActiveChk = MyForm.AddNewCheckBox(MyForm,'ActiveChk','Active');
   ParseBtn = MyForm.AddNewProButton(MyForm, 'ParseBtn', 'Parse JSON');
   ActiveChk.Align = alTop;
   ParseBtn.Align = alBottom;
   ActiveChk.Margins.Left = 15;
   ParseBtn.OnClick = 'ParseJSON';
  ActiveChk.Margins.Top = 10;


   ResultMemo = MyForm.AddNewMemo(MyForm,'ResultMemo','JSON Output');
   LoadBtn = MyForm.AddNewProButton(MyForm, 'LoadBtn', 'Load from File');
   ResultMemo.Align = alClient;
   LoadBtn.Align = alBottom;
   ResultMemo.Height = 200;
   LoadBtn.OnClick = 'LoadJSONFromFile';
  ResultMemo.StyledSettings = ssFamily;
  ResultMemo.TextSettings.WordWrap = True;


   ShowBtn = MyForm.AddNewProButton(MyForm,'ShowBtn','Show JSON');
   SaveBtn = MyForm.AddNewProButton(MyForm, 'SaveBtn', 'Save to File');
   ShowBtn.Align = alBottom;
   SaveBtn.Align = alBottom;
   ShowBtn.Margins.Left = 15;
   SaveBtn.OnClick = 'SaveJSONToFile';
  ShowBtn.Margins.Right = 15;
  ShowBtn.Margins.Bottom = 10;
  ShowBtn.OnClick = 'GenerateJSON';


   MyForm.Run;
   MyForm.Run;
}
}




Line 168: Line 158:


<h2> See Also </h2>
<h2> See Also </h2>
* [[TclJSONArray]]
* [[TclJSONObject]]
* [[TclJSONObject]]
* [[TclJSONArray]]
* [[TclJSONPair]]
* [[TclJSONValue]]
* [[TclJSONValue]]
* [[TclJSONPair]]
 


{{#seo:|title=TCLJSON Library Overview - Clomosy Docs}}
{{#seo:|title=TCLJSON Library Overview - Clomosy Docs}}
{{#seo:|description=Learn how to create, manipulate, validate, and save JSON objects and arrays using TCLJSON, with examples and type-safe value handling.}}
{{#seo:|description=Learn how to create, manipulate, validate, and save JSON objects and arrays using TCLJSON, with examples and type-safe value handling.}}

Revision as of 12:29, 22 October 2025

TCLJSON is a structured and type-safe JSON processing library designed to facilitate the creation, manipulation, and validation of JSON data. It enables the definition of objects, arrays, and values representing standard JSON types, including strings, numbers, booleans, and null elements.

The library provides mechanisms for constructing hierarchical data models, performing key-value pair operations, merging multiple JSON structures, and retrieving nested elements through deep path access. TCLJSON ensures strict compliance with JSON syntax rules, offering validation methods to verify data integrity during parsing and serialization.

In addition to in-memory operations, TCLJSON supports persistent data handling through file-based loading and saving of JSON content. Its strongly typed architecture promotes reliability, consistency, and maintainability in applications that require structured data representation, configuration management, or data exchange using the JSON format.


Information: What is TCLJSON?
TCLJSON allows you to create, manipulate, and serialize JSON data structures. It supports nested objects, arrays, type-safe values, deep path access, merging, cloning, and file operations.
Class Description
TclJSONArray Represents a JSON array with ordered values. Supports adding/removing values or objects, merging, cloning, and enumeration.
TclJSONObject Represents a JSON object with key-value pairs. Provides methods for adding, removing, merging, cloning, and deep path access.
TclJSONPair Represents a single key-value pair inside a JSON object.
TclJSONValue Encapsulates a JSON value (string, integer, number, boolean, datetime, or null) and provides type-safe methods.
Dont Forget!
When working with nested objects or arrays, always free created JSON instances (Obj.Free;, Arr.Free;) after use to prevent memory leaks.


Also, ensure all JSON strings are UTF-8 encoded before parsing to avoid character mismatches during validation.

Feature Use of Definition
ParseToJSONObject obj = TCLJSON.ParseToJSONObject(jsonStr); Parses a JSON string into a TCLJSONObject.
ParseObjectToString jsonStr = TCLJSON.ParseObjectToString(obj); Converts a TCLJSONObject to a JSON string.
ParseToJSONArray arr = TCLJSON.ParseToJSONArray(jsonStr); Parses a JSON string into a TCLJSONArray.
ParseArrayToString jsonStr = TCLJSON.ParseArrayToString(arr); Converts a TCLJSONArray to a JSON string.
LoadObjectFromFile obj = TCLJSON.LoadObjectFromFile('data.json'); Loads a JSON object from a file.
SaveObjectToFile TCLJSON.SaveObjectToFile(obj, 'data.json'); Saves a TCLJSONObject to a file.
IsValidJSON valid = TCLJSON.IsValidJSON(jsonStr); Checks whether a string is valid JSON.


Example: TCLJSON in Action

var
  MyForm: TClForm;
  LoadBtn, SaveBtn, ParseBtn: TClProButton;
  InputMemo, OutputMemo: TClMemo;
  Obj: TCLJSONObject;
  Arr: TCLJSONArray;
  JsonStr: string;
  Valid: Boolean;

void LoadJSONFromFile
{
  Obj = TCLJSON.LoadObjectFromFile('data.json');
  OutputMemo.Lines.Text = Obj.ToJSONString;
}

void SaveJSONToFile
{
  if Obj <> nil
  {
    TCLJSON.SaveObjectToFile(Obj, 'output.json');
    ShowMessage('JSON saved to output.json');
  }
  else
    ShowMessage('No JSON object to save.');
}

void ParseJSON
{
  try
    JsonStr = InputMemo.Text;
    Valid = TCLJSON.IsValidJSON(JsonStr);

    if not Valid
    {
      ShowMessage('Invalid JSON format!');
      exit;
    }

    // Parse string to object
    Obj = TCLJSON.ParseToJSONObject(JsonStr);
    ShowMessage('Parsed Object Key Count: ' + IntToStr(Obj.Count));

    // Convert object back to string
    JsonStr = TCLJSON.ParseObjectToString(Obj);
    OutputMemo.Lines.Text = JsonStr;

    // Create sample array and show conversion
    Arr = TCLJSONArray.Create;
    Arr.AddValue(TCLJSONValue.Str('Item1'));
    Arr.AddValue(TCLJSONValue.Str('Item2'));
    OutputMemo.Lines.Add('');
    OutputMemo.Lines.Add('Array JSON:');
    OutputMemo.Lines.Add(TCLJSON.ParseArrayToString(Arr));

  except
    ShowMessage('Error: ' + LastExceptionMessage);
  }
}

{
  MyForm = TClForm.Create(Self);

  InputMemo = MyForm.AddNewMemo(MyForm, 'InputMemo', 'Enter JSON Text');
  InputMemo.Align = alTop;
  InputMemo.Height = 150;

  OutputMemo = MyForm.AddNewMemo(MyForm, 'OutputMemo', 'Output');
  OutputMemo.Align = alClient;

  ParseBtn = MyForm.AddNewProButton(MyForm, 'ParseBtn', 'Parse JSON');
  ParseBtn.Align = alBottom;
  ParseBtn.OnClick = 'ParseJSON';

  LoadBtn = MyForm.AddNewProButton(MyForm, 'LoadBtn', 'Load from File');
  LoadBtn.Align = alBottom;
  LoadBtn.OnClick = 'LoadJSONFromFile';

  SaveBtn = MyForm.AddNewProButton(MyForm, 'SaveBtn', 'Save to File');
  SaveBtn.Align = alBottom;
  SaveBtn.OnClick = 'SaveJSONToFile';

  MyForm.Run;
}



Output:

TCLJSONExample.png

See Also