如何使用字段名称创建JSON字符串

时间:2019-05-06 04:23:16

标签: javascript json

在我的应用程序中,Asp Web服务返回JSON,其对象名为'd',因此我按如下方式访问'd'对象在应用程序中的对象,

enter image description here

GetBranchOrRegionDataSourceSuccess: function (result, status, init) {
    "use strict";
    var regions = JSON.parse(result.d);
}

我在Ajax成功调用中调用了此函数。

现在的问题是我有一个名为searchLocations的Jquery函数,在该函数内部,我需要调用此函数。并且需要传递参数。

我这样尝试过

var jsonResult = JSON.stringify({'d':result});
  this.GetBranchOrRegionDataSourceSuccess(jsonResult,"Success", true); //here I need to call the function

这是我的完整功能。

function searchName(prov,tree) {
  var result = [];

  let searchKey = new RegExp(prov, "i");

  var objects = JSON.parse(json);
  for (obj of objects) {
    if (obj.Name.match(searchKey)) {

      result.push(obj); 

    } else {
      var toAdd = {"Id": obj.Id, "Name": obj.Name, "Branches": []};
      for (branch of obj.Branches) {
        if (branch.Name.match(searchKey)) {
          toAdd.Branches.push(branch);
        }
      }
      if (toAdd.Branches.length) {
        result.push(toAdd);
      }
    }
  }

  var jsonResult = JSON.stringify({'d':result});
  this.GetBranchOrRegionDataSourceSuccess(jsonResult,"Success", true); //here I need to call the function

}

但这在GetBranchOrRegionDataSourceSuccess行的var regions = JSON.parse(result.d);内部出错,我该如何使用'd'对象名传递结果

1 个答案:

答案 0 :(得分:2)

GetBranchOrRegionDataSourceSuccess期望object具有属性d

d属性值必须是JSON字符串(它将解析)。

您想要

let jsonResult = { d: JSON.stringify(result) }
this.GetBranchOrRegionDataSourceSuccess(jsonResult, 'Success', true)