超对象 - 提取所有(SuperObject - Extract All)

2019-07-17 16:45发布

如何从一个普通的JSON得到所有“身份证”成员的值不知道它的结构 。 由于其非常复杂的,它有很多的子对象。 它必须通过所有子对象循环。

再次为不断问人哪里是例如JSON。 我的问题是关于如何在我的情况“ID”从里边有这个成员的任何通用的JSON提取成员值

Answer 1:

如果你不知道你是从什么地方得到的JSON的结构,需要注意的是JSON是“简单”的复合模式是重要的,你可以遍历它像任何其他复合结构。 下面的示例遍历整个结构以JSON文本并打印名为“ID”的任何构件的路径。

procedure ParseJSON;
var
  JSONText: string;
  JSON: ISuperObject;
begin
  // Retrieve JSON as a string into JSONText variable any way you like.
  JSON := SO(JSONText);
  ProcessObject(JSON.AsObject);
end;

procedure ProcessObject(const aAsObject: TSuperTableString; const aPrefix: string = '');
var
  Names: ISuperObject;
  Name: string;
  Items: ISuperObject;
  Item: ISuperObject;
  idx: Integer;
  Value: string;
  ArrayItem: ISuperObject;
begin
  if Assigned(aAsObject) then
  begin
    Names := aAsObject.GetNames;
    Items := aAsObject.GetValues;

    for idx := 0 to Items.AsArray.Length - 1 do
    begin
      Name := Names.AsArray[idx].AsString;
      Item := Items.AsArray[idx];
      if Item.DataType = stObject then
        Value := '<Object>'
      else if Item.DataType = stArray then
        Value := '<Array>'
      else
        Value := Item.AsString;

      if SameText(Name, 'id') then
        WriteLn(Format('%s: %s', [aPrefix + Name, Value]));

      if Item.DataType = stArray then
        for ArrayItem in Item do
          ProcessObject(ArrayItem.AsObject, aPrefix + Name + '.');

      if Item.DataType = stObject then
        ProcessObject(Item.AsObject, aPrefix + Name + '.');
    end;
  end;
end;


文章来源: SuperObject - Extract All