首页 > 解决方案 > 嵌套 JSON 对象

问题描述

我正在使用 API 来输出 JSON 文件,因此无法编辑 JSON 文件的格式。有什么方法可以遍历每个日内日期,找到每个日期的 open 值?

我尝试过使用Object.intraday[0].open,但这似乎不起作用,因为它不包含在数组中?我意识到我可以使用Object.intraday.date.open(其中日期例如“2018-10-19 15:59:00:”);但是我希望能够索引到不同的时间。

{
    "symbol": "AAPL",
    "stock_exchange_short": "NASDAQ",
    "timezone_name": "America/New_York",
    "intraday": {
        "2018-10-19 15:59:00:" {
            "open": "219.49",
            "close": "219.23",
            "high": "219.61",
            "low": "219.19",
            "volume": "302415"
        },
        "2018-10-19 15:58:00:" {
            "open": "219.62",
            "close": "219.48",
            "high": "219.70",
            "low": "219.48",
            "volume": "173762"
        },
             ....

这是我为了做到这一点而使用的帕斯卡代码,使用测试 JSON{"intraday":{"2018-10-1915:59:00":{"open":"23","low":"4"},"2018-10-1915:58:00":{"open":"25","low":"21"}}}

  JSONValue := TJSONObject.ParseJSONValue('{"intraday":{"2018-10-1915:59:00":{"open":"23","low":"4"},"2018-10-1915:58:00":{"open":"25","low":"21"}}}');
  j:=0;
  begin
    if JSONVAlue is TJSONObject then
      begin
          // Get the quote and low values
          quote := JSONValue.GetValue<string>('intraday[0]');
          low := JSONValue.GetValue<string>('intraday.low');
          Memo1.Lines.Add(quote + ': ' + low);
          j := j+1;
      end;
   end;

标签: jsondelphipascal

解决方案


procedure TfmMain.ParseIntraDay(AMemo: TMemo);
var
  LObject, LIntraDayObj: TJSONObject;
  LEnumerator: TJsonPairEnumerator;
  LQuote, LLow: String;
begin
  LObject := TJSONObject.ParseJSONValue('{"intraday":{"2018-10-19 15:59:00":{"open":"23","low":"4"},"2018-10-19 15:58:00":{"open":"25","low":"21"}}}') as TJSONObject;
  try
    LIntraDayObj := LObject.GetValue('intraday') as TJSONObject; //{"2018-10-19 15:59:00":{"open":"23","low":"4"},"2018-10-19 15:58:00":{"open":"25","low":"21"}}
    LEnumerator := LIntraDayObj.GetEnumerator;
    while LEnumerator.MoveNext do
    begin
      LQuote := LEnumerator.Current.JsonString.Value;
      LLow := (LEnumerator.Current.JsonValue As TJsonObject).Values['low'].Value;
      AMemo.Lines.Add(String.Format('%s: %s', [LQuote, LLow]));
    end;
   finally
     LObject.Free;
   end;
end;

应该在备忘录中给出以下输出:

2018-10-19 15:59:00: 4
2018-10-19 15:58:00: 21

您可以将此作为您想要的基础。


推荐阅读