#1 2014-09-29 19:19:42

Sabbiolina
Member
Registered: 2014-05-20
Posts: 120

Access to nested array in json

Hi

I receive this from mongoDB command:

res: (variant) =

{"set":"rs0",
"date":"2014-09-29T14:11:35",
"myState":1,
"members":
[
{"_id":0,"name":"127.0.0.1:27019"},
{"_id":1,"name":"192.168.172.130:27018"},
{"_id":2,"name":"192.168.172.130:27020"}
],
"ok":1}

How to read "members" ?

  log('Set_ID: '+res.set); //<-- this works

  with TDocVariantData(res.members) do
  begin
   for i := 0 to Count-1 do // <--- count 0
    log(Values[i].name); // <--- no output
  end;

Offline

#2 2014-09-29 19:51:36

Sabbiolina
Member
Registered: 2014-05-20
Posts: 120

Re: Access to nested array in json

this works

  for i:=0 to res.members._Count-1 do
  begin
   log(inttostr(res.members._(i)._id)+': '+res.members._(i).name);
  end;

but,
Why the version of the previous post wrong?

Offline

#3 2014-09-29 20:44:13

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,182
Website

Re: Access to nested array in json

Use docvariantsafe()

Offline

#4 2014-09-29 21:33:15

Sabbiolina
Member
Registered: 2014-05-20
Posts: 120

Re: Access to nested array in json

DocVariantDataSafe ?

But how ?

Offline

#5 2014-09-30 10:38:56

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,182
Website

Re: Access to nested array in json

Something like this:

with DocVariantDataSafe(res.members)^ do
  begin
   for i := 0 to Count-1 do // <--- count 0
    log(Values[i].name); // <--- no output
  end;

In fact, properties are returned as varByRef when late-binding is used, for performance.
TDocVariantData(res.members) won't work, whereas DocVariantDataSafe()^ will follow varByRef redirection.

Offline

Board footer

Powered by FluxBB