代码之家  ›  专栏  ›  技术社区  ›  Niraj

使用AngularJS[duplicate]中的重复键在json响应上迭代

  •  1
  • Niraj  · 技术社区  · 8 年前

    我一直在尝试从angular应用程序中的API调用中获取响应json数据的一部分。

    我尝试了各种组合,但我只能获取最后一条记录,而不能同时获取两条记录。

    这是我的html

    <div ng-controller="MyCtrl">
    <li ng-repeat="x in textvalues">
           {{ x.event.description }}
    </li>
    </div>
    

    还有控制器代码

    var myApp = angular.module('myApp', []);
    
    function MyCtrl($scope, $http) {
    
        $http.get('http://www.vizgr.org/historical-events/search.php?', {params: {format: 'json', query:'India', limit:'2'}}).then(function(response) {
                $scope.textvalues = response.data;
                console.log($scope.textvalues);
            });
    
    }
    

    API调用的响应如下:

    {
      "result": {
        "count": "2",
        "event": {
          "date": "-293",
          "description": "When an invasion of",
          "lang": "en",
          "category1": "By place",
          "category2": "Persia",
          "granularity": "year"
        },
        "event": {
          "date": "-250",
          "description": "The Mauryan s",
          "lang": "en",
          "category1": "By place",
          "category2": "India",
          "granularity": "year"
        }
      }
    }
    

    我试图在UI上打印循环中的事件描述

    这是我的小提琴- http://jsfiddle.net/nirajupadhyay/Jd2Hw/105/

    我尝试了各种反应数据的组合,但无法得到这两种描述。

    请帮忙。

    4 回复  |  直到 8 年前
        1
  •  2
  •   georgeawg    8 年前

    我觉得这个API有点大错特错。一个JSON对象永远不能有两个相同的键,其中包含不同的值。如果选中“网络”选项卡,则会看到响应在对象中只有一个事件键,其值是该对象返回的最后一个值。因此,虽然它可能会在stringized版本中显示2个事件,但它永远不会在JSON对象中为同一个键保存2个值。

    阅读 Does JSON syntax allow duplicate keys in an object?

    不要将format:json传递给API,不要传递format的任何参数。它将以xml格式给出结果。然后通过一些库或下面所示的代码将此xml格式转换为json格式。

    var myApp = angular.module('myApp', []);
    
    function MyCtrl($scope, $http) {
    
      $http.get('http://www.vizgr.org/historical-events/search.php?', {
        params: {
          /* format: 'json', */
          query: 'India',
          limit: '2'
        }
      }).then(function(response) {
        console.log(response.data);
        var dom = parseXml(response.data);
        var json = xml2json(dom)
        console.log(json)
        $scope.events = json.result.event;
      });
    
      function parseXml(xml) {
       var dom = null;
       if (window.DOMParser) {
          try { 
             dom = (new DOMParser()).parseFromString(xml, "text/xml"); 
          } 
          catch (e) { dom = null; }
       }
       else if (window.ActiveXObject) {
          try {
             dom = new ActiveXObject('Microsoft.XMLDOM');
             dom.async = false;
             if (!dom.loadXML(xml)) // parse error ..
    
                window.alert(dom.parseError.reason + dom.parseError.srcText);
          } 
          catch (e) { dom = null; }
       }
       else
          alert("cannot parse xml string!");
       return dom;
    }
    
    function xml2json(xml) {
      try {
        var obj = {};
        if (xml.children.length > 0) {
          for (var i = 0; i < xml.children.length; i++) {
            var item = xml.children.item(i);
            var nodeName = item.nodeName;
    
            if (typeof (obj[nodeName]) == "undefined") {
              obj[nodeName] = xml2json(item);
            } else {
              if (typeof (obj[nodeName].push) == "undefined") {
                var old = obj[nodeName];
    
                obj[nodeName] = [];
                obj[nodeName].push(old);
              }
              obj[nodeName].push(xml2json(item));
            }
          }
        } else {
          obj = xml.textContent;
        }
        return obj;
      } catch (e) {
          console.log(e.message);
      }
    }
    }
    

    检查js fiddle 在这里

        2
  •  2
  •   Michael    8 年前

    正如Nandita Arora Sharma回答的那样,API响应是错误的。

    RFC-7159 (IETF)发布的JSON标准规定:

    “4.物品

    ... 每个名字后面都有一个冒号,用来分隔名字
    从价值上来说。一个逗号将一个值与后面的值分隔开
    名称对象中的名称应该是唯一的。"

    与邮递员进行API测试。呈现JSON,如前所述,只有一个事件。这可能就是angular只能重复一次的原因

    prettyfied response data

    Postman RAW response data 在原始数据中,所有事件对象都具有重复的键。

        3
  •  0
  •   Sajeetharan    8 年前

    你需要通过考试 $http 作为控制器的一个参数,您可以看到特定的错误 "$http is not defined “在控制器中

    function MyCtrl($scope,$http) {
    

    WORKING FIDDLE

    为了回答您的实际问题,您的服务将返回一个对象,而不是数组。它返回一个object of object。所以在这种情况下不能使用ng repeat。它会在

    {“结果”:{“计数”:“3”,“事件”:{“日期”:“-250”,“描述”:“事件” Mauryan“阿育王的狮子之都”是作为一根柱子的一部分而建的 印度北方邦萨尔纳特(大致日期)。现在是 保存于年的萨纳博物馆 萨纳特。“,”朗“:”恩“,”类别1:”由 地点,“类别2”:“印度”,“粒度”:“年份”}

    为了访问事件,您可以使用

       {{textvalues.result.event.description}}
    

    DEMO

        4
  •  0
  •   Nandita Sharma    8 年前

    这个 object 你所指的结构 can never exist

    {
      "result": {
        "count": "2",
        "event": {
          "date": "-293",
          "description": "When an invasion of",
          "lang": "en",
          "category1": "By place",
          "category2": "Persia",
          "granularity": "year"
        },
        "event": {
          "date": "-250",
          "description": "The Mauryan s",
          "lang": "en",
          "category1": "By place",
          "category2": "India",
          "granularity": "year"
        }
      }
    }
    

    如果有的话 key 如果在对象中重复,则会覆盖上一个集合 value 在JSON对象中 key value pair 。API应该返回的内容如下所示,那么只有您才能获得所有事件对象。

    {
      "result": {
        "count": "3",
        "event": [{
          "date": "-250",
          "description": "The Mauryan ''Lion Capital of Asoka'', is erected as part of a pillar at Sarnath, Uttar Pradesh in India (approximate date). It is now preserved at the Sarnath Museum in Sarnath.",
          "lang": "en",
          "category1": "By place",
          "category2": "India",
          "granularity": "year"
        },
        {
          "date": "-250",
          "description": "The Mauryan ''Lion Capital of Asoka'', is erected as part of a pillar at Sarnath, Uttar Pradesh in India (approximate date). It is now preserved at the Sarnath Museum in Sarnath.",
          "lang": "en",
          "category1": "By place",
          "category2": "India",
          "granularity": "year"
        },
        {
          "date": "-250",
          "description": "The Mauryan ''Lion Capital of Asoka'', is erected as part of a pillar at Sarnath, Uttar Pradesh in India (approximate date). It is now preserved at the Sarnath Museum in Sarnath.",
          "lang": "en",
          "category1": "By place",
          "category2": "India",
          "granularity": "year"
        }]
      }
    }
    
    推荐文章