【问题标题】:Formatting JSON for Angular data binding为 Angular 数据绑定格式化 JSON
【发布时间】:2016-03-28 12:12:22
【问题描述】:

当我的 ajax 调用完成时返回一个 json 数组

为了让我的角度数据绑定能够完美运行,我需要将所有值合并到一个 JSON 文件中。我试过 $.extend(),它给出了以下输出

需要解决方案

例如,如果我的回复如下所示:

[0:"{'test':'test'}", 1:"{'test':'test'}", 2:"{'test':'test'}",3: "{'test':'test'}"];

我需要的输出是:

{ test':'test', 'test':'test', 'test':'test', 'test':'test' }

编辑: 最终值将自动关联到 ng-model。

所需的输出示例:

{
"unique_id": 172,
"portfolio": "DIGITAL",
"bus_unit": "dummy",
"project_phase": "",
"test_phase": "SIT",
"project": "Google",
"golivedate": "03/09/2016",
"performance": "Green",
"summary": "jgnbfklgnflknflk",
"last_updated": "",
"risks_issues": "gfmngfnfglkj",
"project_start": "03/16/2016",
"batchLast_run": "",
"custom_project": "1",
"test_execution_id": 5456,
"unique_id": 172,
"test_execution_id": 5456,
"pass": 8,
"fail": 8,
"blocked": 8,
"in_progress": 8,
"no_run": 8,
"not_available": 0,
"total": 8  
}

【问题讨论】:

  • 你能正确发表你的回复吗?
  • 还要描述我需要将所有值合并到一个 JSON 文件中究竟是什么意思?
  • 最终结果应该是对象还是字符串?
  • 因为您的问题不清楚,所以您被否决了。

标签: javascript jquery angularjs json


【解决方案1】:

据我了解,您正在尝试将 Json 数据数组转换为单个 json 数据。因此,您有一组值,但您希望将它们全部放在一个变量中。试试这个

var testData = ["{'test':'test'}", "{'test':'test'}", "{'test':'test'}", "{'test':'test'}"];

var finalData ="";

$.each(testData,function(index,value){
   finalData += value +',';
});

finalData = finalData.replace(/\},\{/g,',').slice(0, -1);

document.write(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • nope 你的答案输出 {'test':'test'},{'test':'test'},{'test':'test'},{'test':'test'我需要的是 {test':'test','test':'test','test':'test','test':'test'}
  • 嗨,我的回复看起来像 [0:"{'test':'test'}", 1:"{'test':'test'}", 2:"{'test': 'test'}",3: "{'test':'test'}"];
  • @VigneshRajarajan 更新了我的答案。让我知道它是否有帮助
  • 你是我的救主,我的救世主:D
  • @VigneshRajarajan 编码愉快!!枫树:D
【解决方案2】:

Map 只是将函数应用于数组中的每个元素。

var arrayOfJSON = ...
var arrayOfObjects = arrayOfJSON.map(function (jsonString){
    return JSON.parse(jsonString)
})
var jsonStringWithAllObjects = JSON.stringify(arrayOfObjects)

【讨论】:

    【解决方案3】:

    如果你使用underscore.js那么就可以轻松

    喜欢:

    var list = [{"test1": "test1"}, {"test2": "test2"}, {"test3": "test3"}];
    var newList = _.extend.apply(null,[{}].concat(list));
    

    然后输出将是

    { test1: "test1", test2: "test2", test3: "test3" }
    

    【讨论】:

    • 你能解释一下吗?我不明白该代码是如何工作的?
    • 将源对象中的所有属性复制到目标对象,并返回目标对象。
    • @shaishabroy 这很困难,因为所有源对象都具有相同的密钥。所以目的地最终将只有一个属性。对吗??
    【解决方案4】:

    遍历数组,将每个值转换为 JSON 对象,连接然后再转换为字符串。

    如果你需要更多次,你可能应该把它变成一个函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 2017-12-26
      • 2013-06-18
      • 2019-12-05
      • 1970-01-01
      相关资源
      最近更新 更多