我正在尝试使用TypeScirp将列表序列化到Json,但我找不到处理复杂嵌套集合的方法。请善待表现出一些亮点。
以下是我尝试转换的示例结构。
[
{
"method": "PATCH",
"uri": "/ScrumStarain/_apis/wit/workItems/$Product Backlog Item?api-version=1.0",
"headers": {
"Content-Type": "application/json-patch+json"
},
"body": [
{
"op": "add",
"path": "/fields/System.Title",
"value": "apip1"
},
{
"op": "add",
"path": "/id",
"value": "-1"
}
]
},
{
"method": "PATCH",
"uri": "/ScrumStarain/_apis/wit/workItems/$Task?api-version=1.0",
"headers": {
"Content-Type": "application/json-patch+json"
},
"body": [
{
"op": "add",
"path": "/fields/System.Title",
"value": "apip2"
},
{
"op": "add",
"path": "/id",
"value": "-2"
}
]
}
]
下面是我试图做的示例,我正在尝试动态生成它。我无法添加正文和从属标记。
var state =" xy" ;
var tagsCollection =["a","b"];
var tempBody : any =[];
tempBody.op = "add";
tempBody.path = "/fields/System.State";
tempBody.value = state;
var jsonMainString:any = {};
jsonMainString.method = "PATCH";
jsonMainString.uri="/_apis/wit/workItems/123?api-version=1.0";
jsonMainString.headers = { "Content-Type" :"application/json-patch+json"};
jsonMainString.body = tempBody;
console.log(JSON.stringify(jsonMainString));
和最终输出如下所示,这是不正确的
{"method":"PATCH","uri":"/_apis/wit/workItems/123?api-version=1.0","headers":{"Content-Type":"application/json-patch+json"},"body":[]}
答案 0 :(得分:1)
尝试JSON.stringify(object)
会让你感到沮丧将代码更改为var tempBody : any ={};
var data= [
{
"method": "PATCH",
"uri": "/ScrumStarain/_apis/wit/workItems/$Product Backlog Item?api-version=1.0",
"headers": {
"Content-Type": "application/json-patch+json"
},
"body": [
{
"op": "add",
"path": "/fields/System.Title",
"value": "apip1"
},
{
"op": "add",
"path": "/id",
"value": "-1"
}
]
},
{
"method": "PATCH",
"uri": "/ScrumStarain/_apis/wit/workItems/$Task?api-version=1.0",
"headers": {
"Content-Type": "application/json-patch+json"
},
"body": [
{
"op": "add",
"path": "/fields/System.Title",
"value": "apip2"
},
{
"op": "add",
"path": "/id",
"value": "-2"
}
]
}
];
console.log(JSON.stringify(data));
答案 1 :(得分:1)
您可能应该查看如何操纵Arrays in JavaScript。 所以我猜你正在尝试的是让身体得到填充。
var state =" xy" ;
var tagsCollection =["a","b"];
var tempBody =[];
tempBody.push({
op: "add",
path: "/fields/System.State",
value: state
});
var jsonMainString = {};
jsonMainString.method = "PATCH";
jsonMainString.uri="/_apis/wit/workItems/123?api-version=1.0";
jsonMainString.headers = { "Content-Type" :"application/json-patch+json"};
jsonMainString.body = tempBody;
console.log(JSON.stringify(jsonMainString));