【发布时间】:2019-03-20 23:40:49
【问题描述】:
我正在处理一个大型 JSON 配置文件(顺便说一下,是 Postman/Newman API 请求的集合),并且需要先对其进行一些修改,然后才能在 Node 应用程序中运行它。
示例配置
let config = {
"name": "API Requests",
"item": [
{
"name": "Upload Data File",
"body": {
"formdata": [
{
"key": "filerename",
"value": "./tests/fixtures/data.txt",
"type": "text"
}
]
}
},
{
"name": "Another Group",
"item": [
{
"name": "Upload Profile Photo",
"body": {
"formdata": [
{
"key": "filerename",
"value": "./tests/fixtures/profilephoto.png",
"type": "text"
},
{
"key": "anotherkey",
"value": "1",
"type": "text"
}
]
}
}
]
}
]
}
function updateFormdataObjects(config) {
let updatedConfig;
// Process the object here and rewrite each of the formdata entries as described below
return updatedConfig;
}
所需步骤
1) 在config 中搜索以查找所有包含"key": "filerename" 的子项
2) 对于每个匹配的孩子,修改它们的键和值如下:
// Original object
{
"key": "filerename",
"value": "./tests/fixtures/anotherphoto.png",
"type": "text"
}
// Updated object
{
"key": "file", // change the value from "filerename" to "file"
"src": "./tests/fixtures/anotherphoto.png", // change the key from "value" to "src"
"type": "file" // change the value from "text" to "file"
}
3) 完成后,返回整个修改后的对象。
注意事项
- 主对象中可能有许多匹配的子对象。所有这些都需要处理。
- 对象可以有无限层的嵌套,所以函数应该适应这一点。
- 该函数应返回一个修改后的对象,然后可以在其他地方使用该对象
- 我将此脚本作为 ES6 的 Node 应用程序的一部分运行,因此可以充分利用
【问题讨论】:
-
您是否只是在 JSON 文件中查找和替换文本?不能用 sublime、VSCode 等文本编辑器吗?
-
@DannyDainton 不幸的是不是,因为请求集(大约有 400 个)会定期更新并导出为 JSON。然后,此脚本需要处理该 JSON 文件并在 CLI 上运行 Newman 之前进行必要的调整。上面的示例是真实配置的大量缩略版本;)
-
导出什么?不能在那个阶段之前而不是之后处理吗?
-
很遗憾没有 - 生成应用程序(邮递员)有一些限制,这意味着我们必须在导出后通过脚本进行修改。
标签: javascript postman newman