在 delphi 的 json 文件中获取键名

Get key names in json file in delphi

我有这样的 json 字符串格式:

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

我需要获取名字,"Joseph"、"John"、"Fred" 等等...我有一个函数可以将名字添加到列表中,我没有知道将添加哪些名称,所以我需要获取这些名称。

我只能使用此代码获取名称 "LIST":

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

我在 delphi 7

中使用 lkJSON-1.07

可以依次获取名字,每个名字获取下一个对象

  1. 获取名称:js.NameOf[0]

  2. 根据名称获取对象:js[js.NameOf[0]]


getJSONNames 过程递归打印 TlkJSONobject 对象中包含的所有名称。

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.