json字符串中的数组长度返回角度ng-repeat中的意外结果

时间:2016-10-19 15:28:03

标签: javascript angularjs json

我有以下json:

[
    {
        "id": 1,
        "name": "Vojislav Kovacevic",
        "street": "Sava Burica",
        "city": "Belgrade",
        "state": "Zemun",
        "zip": "11080",
        "country": "Serbia",
        "giftwrap": null,
        "products": "[
            {\"count\":2,\"id\":1,\"price\":275,\"name\":\"Kayak\"},
            {\"count\":1,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"}
        ]"
    },
    {
        "id": 2,
        "name": "dzimi",
        "street": "dzimi strit",
        "city": "belgrade",
        "state": "zemun",
        "zip": "11000",
        "country": "serbia",
        "giftwrap": null,
        "products": "[
            {\"count\":5,\"id\":1,\"price\":275,\"name\":\"Kayak\"},
            {\"count\":3,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"},
            {\"count\":4,\"id\":3,\"price\":19.5,\"name\":\"Soccer Ball\"}
        ]"
    },
    {
        "id": 3,
        "name": "mimi",
        "street": "cincar janka 7",
        "city": "novi sad",
        "state": "novi sad",
        "zip": "11000",
        "country": "serbia",
        "giftwrap": null,
        "products": "[
            {\"count\":2,\"id\":1,\"price\":275,\"name\":\"Kayak\"},
            {\"count\":1,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"}
        ]"
    }
]

然而,当我像这样循环时:

<tr ng-repeat="order in orders">
    <td>{{ order.products.length }}</td>
</tr>

我得到100, 153, 100作为结果(分别),我期待2,3,2因为每个products内有多少个对象。

5 个答案:

答案 0 :(得分:0)

因为产品包含字符串值而不是数组,因此您将获得为字符串值返回的字符长度。

产品必须采用以下格式:

{
    "id": 2,
    "name": "dzimi",
    "street": "dzimi strit",
    "city": "belgrade",
    "state": "zemun",
    "zip": "11000",
    "country": "serbia",
    "giftwrap": null,
    "products": [
            {"count":5,"id":1,"price":275,"name":"Kayak"},
            {"count":3,"id":2,"price":48.95,"name":"Lifejacket"},
            {"count":4,"id":3,"price":19.5,"name":"Soccer Ball"}
        ]
  }

答案 1 :(得分:0)

products的值是字符串,您将获得字符串的长度。这是一个编码问题,可能来自您的后端。

您可以尝试JSON.parse(order.products).length

请注意,这并不能解决实际问题(位于后端)。要解决这个问题,我们需要查看后端代码,但你可能应该为此做一个不同的问题(当我将json编码为this时,我在客户端得到that但是我需要that2

答案 2 :(得分:0)

看起来你正在尝试获取数组本身的长度,但由于你将product值作为字符串(即用引号括起来),调用字符串的长度只会返回数字字符。

如果您需要products数组中的对象数,请尝试删除products数组周围的引号,并保持代码相同。希望这有帮助!

答案 3 :(得分:0)

您应该更改API的响应,还是应该将string解析为JSON

<tr ng-repeat="order in orders">
      <td>{{ JSON.parse(order.products).length }}</td>
</tr>

答案 4 :(得分:0)

您可以在每个产品值之前添加JSON.parse():

    // .............
    // .............
    "country": "Serbia",
    "giftwrap": null,
    "products": JSON.parse("[
        {\"count\":2,\"id\":1,\"price\":275,\"name\":\"Kayak\"},
        {\"count\":1,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"}
    ]")
},
{
    // ............

工作jsfiddle:https://jsfiddle.net/newjavaonemahesh/hso9e375/19/