【问题标题】:Extract Values from key and array on JSON begins with '['从 JSON 上的键和数组中提取值以“[”开头
【发布时间】:2021-05-20 14:31:16
【问题描述】:

对不起,我在网站上搜索了这个问题 但是我拥有的 Json 与网站上的其他 Json 不同,因为它以 '['

我厌倦了尝试提取值 那么我如何从 JSON 上的键和数组中提取值以 '['

开头
[{"date":"12/11/1990","name":"Delphi7"},{"date":"03/05/2012","name":"Delphi 10.4"}]

或提取表单:

[{"User":{"date":"12/11/1990","name":"Delphi7"}},{"User":{"date":"03/05/2012","name":"Delphi 10.4"}}]

【问题讨论】:

    标签: arrays json delphi pascal


    【解决方案1】:

    在 JSON 中,[] 表示一个数组。在这种情况下,您提供的两个示例都代表一个对象数组。

    如果您使用TJSONObject.ParseJSONValue() 解析这些字符串,它将返回一个TJSONValue 指针,该指针指向一个包含TJSONObject 元素的TJSONArray 对象,例如:

    uses
      ..., System.JSON;
    
    var
      JSONStr, DateStr, NameStr: string;
      JSONVal: TJSONValue;
      JSONArr: TJSONArray;
      JSONObj: TJSONObject;
      I: Integer;
    begin
      JSONStr := '[{"date":"12/11/1990","name":"Delphi7"},{"date":"03/05/2012","name":"Delphi 10.4"}]';
      JSONVal := TJSONObject.ParseJSONValue(JSONStr);
      try
        JSONArr := JSONVal as TJSONArray;
        for I := 0 to JSONArr.Count-1 do
        begin
          JSONObj := JSONArr[I] as TJSONObject;
          DateStr := JSONObj.GetValue('date').Value;
          NameStr := JSONObj.GetValue('name').Value;
          ...
        end;
      finally
        JSONVal.Free;
      end;
    end;
    
    uses
      ..., System.JSON;
    
    var
      JSONStr, DateStr, NameStr: string;
      JSONVal: TJSONValue;
      JSONArr: TJSONArray;
      JSONObj, JSONUser: TJSONObject;
      I: Integer;
    begin
      JSONStr := '[{"User":{"date":"12/11/1990","name":"Delphi7"}},{"User":{"date":"03/05/2012","name":"Delphi 10.4"}}]';
      JSONVal := TJSONObject.ParseJSONValue(JSONStr);
      try
        JSONArr := JSONVal as TJSONArray;
        for I := 0 to JSONArr.Count-1 do
        begin
          JSONObj := JSONArr[I] as TJSONObject;
          JSONUser := JSONObj.GetValue('User') as TJSONObject;
          DateStr := JSONUser.GetValue('date').Value;
          NameStr := JSONUser.GetValue('name').Value;
          ...
        end;
      finally
        JSONVal.Free;
      end;
    end;
    

    【讨论】:

    • 谢谢 Remy Lebeau 在此更改 JSONObj := JSONArr.Items[I] as TJSONObject; 之前它对我不起作用DateStr := JSONObj.GetValue('date').Value; NameStr := JSONObj.GetValue('name').Value;
    • 修复了Get(),谢谢。 JSONArr.Items[I]JSONArr[I] 做同样的事情,因为 Items[]TJSONArraydefault property
    • 所有对你的尊重和感谢
    猜你喜欢
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多