TypeScript如何将对象数组格式化为json

时间:2017-03-09 07:26:57

标签: json mongodb angular typescript

我发布了_attachments变量等数据: enter image description here

我想准备要插入的数据作为以下结构:

"_attachments": [
  {
    "container": "string",
    "fileName": "string",
    "name": "string",
    "mime": "string",
    "size": 0
  }
]

但我做了什么:

for(let key in _attachments) {
  job._attachments[key]['container']  = _attachments[key]['container'];
  job._attachments[key]['fileName']  = _attachments[key]['fileName'];
  job._attachments[key]['name']      = _attachments[key]['name'];
  job._attachments[key]['mime']      = _attachments[key]['mime'];
  job._attachments[key]['size']      = _attachments[key]['size'];
}

发出此错误:

 Unprocessable Entity

注意:我使用环回。

4 个答案:

答案 0 :(得分:4)

只需将其添加到attachment.josn

即可
"id": {
  "type": "string",
  "id": true,
  "defaultFn": "uuid"
}

并且无需循环数据。

答案 1 :(得分:3)

从屏幕截图_attachments似乎是一个数组;如果是这种情况,则不应使用for...in来迭代它,而是for..offor..in将返回所有可枚举的属性,包括可能的"不需要的"那些

有关详细信息,请参阅此excellent MDN resource的底部(Typescript中提供for..of

for (let index of _attachments) {
...
}

更好的是,使用地图

const result  = _attachments.map( att => ...)

您映射的结构看起来与原始结构完全相同,为什么不使用直接赋值?

答案 2 :(得分:0)

您需要对其进行字符串化。

<强>代码

data = { 
    container: "Stuff"
}

var jsonString = JSON.stringify(data); 

console.log(jsonString);

<强>之前

enter image description here

<强>后

enter image description here

这更像是您的数据,

enter image description here

答案 3 :(得分:0)

JSON.stringify将帮助您以json格式获取对象,JSON.parse将从JSON转换回对象。