Access tjsarray in tjsobject?

I'm writing a websocket based chat to get familiar with TMS Web Core and websockets in Nodejs.

I've run into an issue though, where I have a data structure like this coming in:

{
  "success": true,
  "type": "userlist",
  "users": [
    "Marcus",
    "Bob"
  ]
}



It comes in as a TJSObject in the socket onDataReceived procedure.

I have a procedure that will loop over the array of users and update a tweblistbox, but how do I access those values?

I can get at the bool and strings easily but not sure about the array, and I can't find much of any Pas2JS tutorials online.
To make this a little more interesting, I think I found a bug with TJSON.Parse

If I do this:


procedure TForm1.WebButton1Click(Sender: TObject);
var
  js: TJSON;
  jo: TJSONObject;
begin
  js := TJSON.Create;
  jo := JS.Parse('{"myKey":"myValue", "anArray": ["one", "two"]}');
  OutputDebugString(jo.ToJSON);
end;



I get this output:

{"myKey":"myValue","anArray":{}}

This code shows the array values:


var
  js: TJSON;
  jo: TJSONObject;
  ja: TJSONArray;
  i: integer;
begin
  js := TJSON.Create;
  jo := JS.Parse('{"myKey":"myValue", "anArray": ["one", "two"]}');
  ja := TJSONArray( jo.GetValue('anArray') );
  for i := 0 to ja.Count - 1 do
    weblistbox1.Items.Add(ja.Items[i].Value);
end;


Bruno Fierens2019-12-27 09:52:34

Thanks Bruno, that works.


But what about the ToJson issue?

Marcus, the TJSONObject.ToJSON function assumes key-value pairs. If I modify your code by adding a key to each array element (i.e. each array element is an object), then it should work:


procedure TForm1.WebButton1Click(Sender: TObject);
var
  js: TJSON;
  jo: TJSONObject;
begin
  js := TJSON.Create;
  jo := JS.Parse('{"myKey":"myValue", "anArray": [{"0":"one"}, {"1","two"}]}');
  OutputDebugString(jo.ToJSON);
end;

So we can't trust ToJSON to accurately serialize an object.


Frankly, that's horrifying.

Can we have some time to investigate this please?

This did not happen so far as it is a holiday period here and most of our team are having well deserved vacations.

Yes, of course!


Now that I know what's going on I can work around it.

We traced & fixed this issue. The next update will address this.

That's great to hear, thanks for the quick response!