ahausladen / JsonDataObjects

JSON parser for Delphi 2009 and newer
MIT License
413 stars 160 forks source link

index out of range when accessing array of jsonobject #61

Closed draHL closed 3 years ago

draHL commented 3 years ago

when try to access arraay of jsonObject error occurred "list index out of bound" here sample code. or i did it wrong ?

jObj: TJsonObject; jarr : TJSONarray; jbase : TJsonBaseObject; i,j : integer; fieldname, fieldvalue :String; begin str:='[{"id":1,"text":"test1"}, {"id":2,"text":"test1"}, {"id":3,"text":"test1"} ]'; jbase := TJsonObject.Parse(str); jarr := tjsonarray(jbase); try for i := 0 to jarr.Count-1 do begin
jobj:=jarr.ExtractObject(i); // -->error here list index out of bound (2) for j := 0 to Pred(jobj.Count) do begin fieldname:=jobj.Names[j]; fieldvalue:=Vartostr(jobj[fieldname]); end; if assigned(jobj) then FreeAndNil(jobj); end; finally if assigned(jbase) then FreeAndNil(jbase); end

MvRens commented 3 years ago

ExtractObject removes the object from jarr, so by the time you get to index 2 the count is already down to 1.

If you want to remove the objects, loop from "Count - 1 downto 0" instead. If you just want to access the values, use "jobj := jarr[i]" and don't Free the jobj.

Hope that helps!

draHL commented 3 years ago

thx a lot it works. cheers