1 (edited by prahousefamily 2024-07-01 10:43:57)

Topic: How to Sort Order by Name value in JSonArray and add to Memo1

How to Sort Order by Name value in JSonArray and add to Memo1


Example

[
    {
        "Name": "Cat",
        "Color": "White"
    },
    {
        "Name": "Ant",
        "Color": "Red"
    },
    {
        "Name": "Zebar",
        "Color": "Black"
    }
]

I will To result

Ant,Red
Cat,White
Zebar,Black






------------------------------------------------------------

Try Easy Code But  Result  Not Order By Name

Cat,White
Ant,Red
Zebar,Black

How To Edit Code ???

procedure MyProcedure();
var
JsonArray : TJsonArray  ;
i         : Integer     ;
JS_temp   : TJsonObject ;
js_name   : TJsonString ;
js_color  : TJsonString ;
begin
    JsonArray := TJsonArray.ParseJSONValue(
    '[
    {
        "Name": "Cat",
        "Color": "White"
    },
    {
        "Name": "Ant",
        "Color": "Red"
    },
    {
        "Name": "Zebar",
        "Color": "Black"
    }
    ]'
    );
    for i := 0 to JsonArray.Size -1 do
    begin
        js_temp := TJSONObject (TJSONObject(JsonArray.Get(i))) ;
        js_name := TJSONString(JS_temp.GetPairByName('balance').JsonValue);
        js_color := TJSONString(JS_temp.GetPairByName('color').JsonValue);
        Form1.Memo1.Lines.add(js_name.Value+','+js_color.Value)
    end;
end;
My Visual Database : I Love You
Easy For Beginner Student For Me

2 (edited by sparrow 2024-07-01 16:38:53)

Re: How to Sort Order by Name value in JSonArray and add to Memo1

Hi,

Your code is not working.


Something like this.


procedure Form1_Button1_OnClick (Sender: TObject; var Cancel: boolean);
var
  JArray : TJsonArray  ;
  i         : Integer     ;
  TStrL     : TStringList;
  js_name   : string ;
  js_color  : string ;
  str       : string = '[{"Name": "Cat","Color": "White"},{"Name": "Ant","Color": "Red"},{"Name": "Zebar","Color": "Black"}]';
begin
  TStrL := TStringList.Create;
  TStrL.Sorted := true;
  JArray := TJSONarray(TJsonObject.ParseJSONValue(str));
  for i := 0 to JArray.Size -1 do
  begin
    js_name := TjsonObject(JArray.Get(i)).GetPairByName('Name').JsonValue.ToString;
    js_color := TjsonObject(JArray.Get(i)).GetPairByName('Color').JsonValue.ToString;
    TStrL.add(js_name+','+js_color);
  end;
  frm_main.Memo1.Lines.Text := TStrL.text;
  TStrL.Free;
end;