Search code examples
jsondelphidelphi-7

Get key names in json file in delphi


I have a json string format like this:

{
  "LIST":{
    "Joseph":{  
      "item1":0,
      "item2":0
    },
    "John":{
      "item1":0,
      "item2":0
    },
    "Fred":{
      "item1":0,
      "item2":0
    }
  }
}

I need to get the names, "Joseph", "John", "Fred" and so on... I have a function that will add names to the list, I have no idea what names will be added so I need to get those names.

I can only get the name "LIST" with this code:

js := TlkJSONstreamed.loadfromfile(jsonFile) as TlkJsonObject;
try
 ShowMessage( vartostr(js.NameOf[0]) );
finally
 s.free;
end;

I'm using lkJSON-1.07 in delphi 7


Solution

  • You can get the names in turn and obtain the next object for each name.

    1. Get the name: js.NameOf[0]

    2. Obtain the object from the name: js[js.NameOf[0]]


    The getJSONNames procedure prints all the names contained in a TlkJSONobject object recursively.

    procedure getJSONNames(const Ajs: TlkJSONobject);
    var
      i: Integer;
    begin
      if Ajs = nil then
        Exit
      else
        for i := 0 to Ajs.Count-1 do begin
          WriteLn(Ajs.NameOf[i]);
          getJSONNames(TlkJSONobject(Ajs[Ajs.NameOf[i]]));
        end;
    end;
    
    var
      js: TlkJsonObject;
    begin
      js := TlkJSONstreamed.loadfromfile(jsonFile) as TlkJsonObject;
      try
        getJSONNames(js);
      finally
        js.free;
      end;
    end.