【问题标题】:ng repeat json parse show empty stringng 重复 json 解析显示空字符串
【发布时间】:2017-09-06 03:32:55
【问题描述】:

我有来自数组列表的对象数组。我使用 JSON.parse 对象的方法将对象字符串转换为对象,但它在 ng-repeat 中显示为空。

翡翠

.item.col-md-4(ng-repeat='p in searchData | filter: paginate | orderBy: sortKey ')
   // `p` is a object of string, for example "{id:2, name:'abel'}";
   - var property = JSON.parse("{{ p }}"); // Error at this line
   +AddPropertyCard(property)

搜索数据

[{id:0, name:"abel"},{id:1, name:"julia"}]

错误

var 属性 = JSON.parse("");

位置 1 的 JSON 中的意外令牌 {

【问题讨论】:

  • 你能告诉我们你的 JSON 吗?
  • p 好像是空的,先检查p 的值。
  • @leaf {{ p }} 返回对象。
  • 这不起作用,jade 试图解析服务器上的属性,而不是客户端,但 ng-repeat 没有在服务器上展开。除此之外,无论如何您都不需要需要 JSON.parse; ng-repaeat 应该已经有单独的 p 对象,{{p.id}}{{p.name}} 应该直接输出。
  • 很可能,您只需要+AddPropertyCard(p)JSON.parse 的行就可以完全消失。

标签: javascript angularjs json pug


【解决方案1】:

更新 1

变量 'p' 似乎是对象。

您必须使用点符号来访问它。 像 {{p.id}}{{p.name}}。这将显示相​​应的值。


JSON.parse 需要对象字符串才能解析它。

// Lets create a simple Object in javascript
var notStringObj = {
    "name": "John",
    "age": 30,
    "city": "New York"
};
console.log("JavaScript Object", notStringObj);

// Lets stringify (Convert in string) the object
var stringObj = JSON.stringify(notStringObj);
console.log("JavaScript Stringified Object", stringObj);

// Following is code to decode this object

// This will give you result you are expecting i.e. JavaScript Object
var obj1 = JSON.parse(stringObj);

// This will throw error - Unexpected token { in JSON at position 1
// Because this was plain object not a string
// JSON.parse expects object string in order to Parse it
var obj2 = JSON.parse(notStringObj)

【讨论】:

  • 它不再显示错误。使用 JSON.stringify,它显示为空。 p 变量具有来自 ng-repeat 的对象。但什么也没显示
  • @Abel Chun 'p' 是一个对象。您必须使用点符号访问它。尝试访问 {{p.id}}、{{p.name}}。然后它不会显示任何错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 2020-05-23
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多