Dan Kelly
Dan Kelly

Reputation: 2702

Parsing Datasnap result using JavaScript

I'm trying to return a list of data from Delphi to a listbox and I think I'm failing to grasp a fundamental of how it all fits together.

This answer has got me a working example using a locally defined dataset.

The issue I now have is the structure of the JSON object returned by my Delphi code.

In the above answer there is only 1 "tier" of data in the object:

resultJSON = '{"1":"Firm 1","2":"Firm 2","3":"Firm 3"}';

However my Delphi Code seems to add an tier. The query is as follows:

function TServerMethods1.GetFirms(jobnumb: string): TJSONObject;
var
   jso: TJSONObject;
begin
   jso := TJSONObject.Create();
   GetJobFirmList(jobnumb);
   with SQLQuery1 do
      while not Eof do
      begin
         jso.AddPair(TJSONPair.Create(FieldByName('firmref').AsString,
                                  FieldByName('firmnaem').AsString));
         Next;
      end;
   Result := jso;
end;

This returns the following result format:

 {"result":[{"1":"Firm 1","2":"Firm 2","3":"Firm 3"}]}

I either need to reduce the code outside the square braces, or understand how to iterate the levels better.

This answer here shows how to parse two tiers in a similar structure but the best I can come up with integrating the two is the following which fails:

function getJobFirms()
{
  var sel = $("#FirmList");
  sel.empty();
  var resultJSON = '{"result":[{"1":"Firm 1","2":"Firm 2","3":"Firm 3"}]}';
  var result = $.parseJSON(resultJSON);
  $.each(result, function() {      
    $.each(result.result, function(k,v) {
      var opt = document.createElement('option');
      opt.value = k;
      opt.text = v;
      sel.append(opt);
     });
  });
}

Upvotes: 2

Views: 545

Answers (1)

Milos Popovic
Milos Popovic

Reputation: 184

Like you said, it appears that you are incorrectly iterating your JSON structure. Namely, result.result is an array, so you can try something like this:

function getJobFirms()
{
    var sel = $("#FirmList");
    sel.empty();
    var resultJSON = '{"result":[{"1":"Firm 1","2":"Firm 2","3":"Firm 3"}]}';
    var result = $.parseJSON(resultJSON);
    $.each(result.result, function(i, resultItem) {
        $.each(resultItem, function(k, v) {
            var opt = document.createElement('option');
            opt.value = k;
            opt.text = v;
            sel.append(opt);
        });
    });
}

Also, if you have only one element in result.result array, you can reduce code even more:

function getJobFirms()
{
    var sel = $("#FirmList");
    sel.empty();
    var resultJSON = '{"result":[{"1":"Firm 1","2":"Firm 2","3":"Firm 3"}]}';
    var result = $.parseJSON(resultJSON);
    $.each(result.result[0], function(k, v) {
        var opt = document.createElement('option');
        opt.value = k;
        opt.text = v;
        sel.append(opt);
    });
}

Upvotes: 1

Related Questions