From Clomosy Docs

Revision as of 12:15, 10 March 2025 by ClomosyManager (talk | contribs)

The Clomosy.CLParseJSON function is used to process data in JSON format. This function parses the JSON data according to a specified structure and retrieves the specified field (path). For example, it is used to obtain the value of a specific index or key within a JSON object.


JsonData : Data is retrieved in JSON format. Example:

{
 "products": [
   {
     "id": 101,
     "name": "Laptop",
     "price": 15000,
     "stock": 25
   }
 ]
}

JsonPath  : A string value specifies the path to the desired field within the JSON data. For example, to access the price field of the item at index 0 in the above example, it should be defined as 'products.0.price'.


Example 1

var
  Form1:TCLForm;
  ReceivedDataMemo,jsonDataMemo: TclMemo;
  Btn1 : TclButton;
  JsonPathLbl : TclLabel;
  strJSONData,strJsonPath : String;

void GetJsonData;
{
  ReceivedDataMemo.Lines.Text = Clomosy.CLParseJSON(strJSONData,strJsonPath);
}

{
  Form1 = TCLForm.Create(Self);
  strJSONData = '{
  "products": [
    {
      "id": 101,
      "name": "Laptop",
      "price": 15000,
      "stock": 25
    },
    {
      "id": 102,
      "name": "Smartphone",
      "price": 12000,
      "stock": 50
    },
    {
      "id": 103,
      "name": "Headphones",
      "price": 1000,
      "stock": 100
    }
  ]
}';
  strJsonPath = 'products.0'; // or 'products' or 'products.2.name'
  //products.3.name => If the specified index is not present in the JSON structure, an 'Error: Invalid array index.' error is returned.
  jsonDataMemo= Form1.AddNewMemo(Form1,'jsonDataMemo','--');
  jsonDataMemo.Align = alMostTop;
  jsonDataMemo.Height = Form1.clHeight / 3;
  jsonDataMemo.Margins.Left= 5;
  jsonDataMemo.Margins.Right= 5; 
  jsonDataMemo.ReadOnly = True;
  jsonDataMemo.WordWrap = True;
  jsonDataMemo.Lines.Text = strJSONData;
  
  JsonPathLbl= Form1.AddNewLabel(Form1,'JsonPathLbl','--');
  JsonPathLbl.Align = alMostTop;
  JsonPathLbl.Height = 70;
  JsonPathLbl.Margins.Left= 5;
  JsonPathLbl.Margins.Right= 5; 
  JsonPathLbl.StyledSettings = ssFamily;
  JsonPathLbl.TextSettings.Font.Size=20;
  JsonPathLbl.WordWrap = True;
  JsonPathLbl.Autosize = True;
  JsonPathLbl.Text = strJsonPath;
  
  ReceivedDataMemo = Form1.AddNewMemo(Form1,'ReceivedDataMemo','');
  ReceivedDataMemo.Align = alTop;
  ReceivedDataMemo.Height = Form1.clHeight / 3;
  ReceivedDataMemo.Margins.Left= 10;
  ReceivedDataMemo.Margins.Right= 10; 
  ReceivedDataMemo.Margins.Top= 10;
  ReceivedDataMemo.ReadOnly = True;
  ReceivedDataMemo.TextSettings.WordWrap = True;
  
  Btn1 = Form1.AddNewButton(Form1,'Btn1','Get Json Data');
  Btn1.Align = AlBottom;
  Btn1.Height = 80;
  Btn1.Margins.Right = 10;
  Btn1.Margins.Left = 10;
  Form1.AddNewEvent(Btn1,tbeOnClick,'GetJsonData');
  
  Form1.Run;
}

Output: The generated JSON output is as follows.


See Also