Jump to content
JIMSMITH

Parsing a json file

Recommended Posts

I have a json file that may contain multiple groups.  I am using Delphi 10.1 for reference.  I want to be able to go to a certain group and loop all of the json objects and retrieve values.  I don't see findvalue in this version.  My question is what is the best way to search to the group 1 section and loop all of the json objects to retrieve their values.

 

{"Group1":{"001":{"ImgHot":"hodincodtext","ImgNormal":"hodincodtext2","ImgChannel":"hodincodtext3","Caption":"Cats"},"002":{"ImgHot":"hodincodtext","ImgNormal":"hodincodtext2","ImgChannel":"hodincodtext3","Caption":"Dogs"}}}

 

 

peoplets.json

Edited by JIMSMITH
combine a word for clarity

Share this post


Link to post

I don't know if it was included in Delphi 10.1 or it came later, but you can use TJSONObject in the System.JSON unit.

 

You'll find plenty of examples to get you started on how to process your specific document.

Share this post


Link to post

I had to fire up my dev machine so I did a small test for you. The following code can be simplified a lot but at least it's easy to see what's going on:

procedure TForm1.Button1Click(Sender: TObject);
Var
  fulljson, group1, items: TJSONObject;
  enumpair: TJSONPair;
begin
  fulljson := TJSONObject(TJSONObject.ParseJSONValue(Memo1.Lines.Text));
  If Not Assigned(fulljson) Then
    Exit;

  Memo2.Lines.Add('JSON parsed successfully.');

  group1 := TJSONObject(fulljson.GetValue('Group1'));
  If Not Assigned(group1) Then
    Exit;

  Memo2.Lines.Add('Group1 found!');

  For enumpair In group1 Do
  Begin
    Memo2.Lines.Add('Found ' + enumpair.JsonString.Value + ' under Group1');

    items := TJSONObject(enumpair.JsonValue);

    Memo2.Lines.Add('ImgHot: ' + items.GetValue<String>('ImgHot'));
    Memo2.Lines.Add('ImgNormal: ' + items.GetValue<String>('ImgNormal'));
    Memo2.Lines.Add('ImgChannel: ' + items.GetValue<String>('ImgChannel'));
    Memo2.Lines.Add('Caption: ' + items.GetValue<String>('Caption'));
  End;

It successfully walks through your JSON file:

 

image.thumb.png.9192734832c730f7ec0106dafbd66087.png

  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×