Variable for loop not called

I am using DBXJson to parse a simple json file named response.json

and display its contents in a grid, but only the first row of the grid is ever populated with data, and even if to display more rows / data, I am using a custom grid in the code below, but I tried a variation of the code below using a standard stringgrid and it showed the same behavior. This is the code I am using to parse the response and display it in my grid.

var
  sl: TStringList;
  LJsonArr: TJSONArray;
  LJsonValue: TJSONValue;
  LItem: TJSONValue;
  col, row: Integer;
begin
  col := 0;
  row := 0;

  sl := TStringList.Create;
  sl.LoadFromFile('response.txt');
  LJsonArr := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(sl.text), 0)
    as TJSONArray;

  for LJsonValue in LJsonArr do
  begin
    NextGrid1.AddRow();

    for LItem in TJSONArray(LJsonValue) do
    begin
      NextGrid1.Cells[col, row] := TJSONPair(LItem).JsonValue.Value;
      inc(col);
    end;
    inc(row);
  end;
  sl.Free;
end;

      

I suspect the problem is that the variable is row

out of place and not called and it only calls the first line, but I could be wrong and I hope a fresh pair of eyes can reveal the problem.

+3


source to share


1 answer


The problem is that it col

has to be reinitialized to zero every time you start a new line. So move the initialization col

to the outer loop.

row := 0;
for LJsonValue in LJsonArr do
begin
  col := 0;
  NextGrid1.AddRow();
  for LItem in TJSONArray(LJsonValue) do
  begin
    NextGrid1.Cells[col,row] := TJSONPair(LItem).JsonValue.Value;
    inc(col);
  end;
  inc(row);
end;

      

I don't know about this JSON library, but if it allows you to access array elements with random access, then a traditional oindexed for the loop will result in cleaner code that you use for the for loop. In pseudocode:



for row := 0 to arr.length do
begin
  item := arr[row];
  for col := 0 to item.length do
    grid.Cells[col,row] := item[col];
end;

      

Generally, for in loop is better if you don't need to know the index of the element. However, once you need to know the index of an element, traditional indexing for loops is usually preferred.

+4


source







All Articles