Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSON string in Delphi?

Tags:

How can I parse the JSON string

{"data":{"results":[{"Branch":"ACCT590003"}]}} 

using the TJSONObject object? I want to get the ACCT590003 value from this string.

like image 376
Salvador Avatar asked Dec 03 '10 23:12

Salvador


2 Answers

You don't need to use external libraries to perform a JSONPath search. Example with Delphi 10 Seattle:

uses  System.JSON; procedure ParseJSonValue; var    JSonValue:TJSonValue;    st:string;    Branch: string; begin    st := '{"data":{"results":[{"Branch":"ACCT590003"}]}}';    JsonValue := TJSonObject.ParseJSONValue(st);    Branch := JsonValue.GetValue<string>('data.results[0].Branch');    JsonValue.Free; end; 
like image 88
jaruzafa Avatar answered Sep 19 '22 20:09

jaruzafa


uses   SysUtils,   DBXJSON;  type   TProcessJSONString = TProc<TJSONString>;  procedure DoJSONObject(o: TJSONObject; Process: TProcessJSONString); forward;  procedure DoJSONArray(o: TJSONArray; Process: TProcessJSONString); var i: integer;     v: TJSONValue; begin   for i := 0 to o.Size - 1 do begin     v := o.Get(i);     if v is TJSONObject then       DoJSONObject(v as TJSONObject, Process);   end; end;  procedure DoJSONObject(o: TJSONObject; Process: TProcessJSONString); var i: integer;     p: TJSONPair; begin   for i := 0 to o.Size - 1 do begin     p := o.Get(i);     Process(p.JsonString);     if p.JsonValue is TJSONObject then       DoJSONObject(p.JsonValue as TJSONObject, Process)     else if p.JsonValue is TJSONArray then       DoJSONArray(p.JsonValue as TJSONArray, Process)     else if p.JsonValue is TJSONString then       Process(p.JsonValue as TJSONString);   end; end;  var o: TJSONObject; begin   o := TJSONObject.ParseJSONValue('{"data":{"results":[{"Branch":"ACCT590003"}]}}') as TJSONObject;   try     DoJSONObject(o,       procedure (o: TJSONString)       begin         WriteLn(o.ToString);       end     );   finally     o.Free;   end;   ReadLn; end. 
like image 41
Chau Chee Yang Avatar answered Sep 18 '22 20:09

Chau Chee Yang