我正在使用一个大型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)完成后,返回整个修改后的对象。
答案 0 :(得分:1)
我想避免对JSON进行字符串化处理,然后再对它进行正则表达式替换,因为我认为这在将来会变得不那么通用。但这似乎是目前最简单的方法:
function replaceFilePaths(input) {
let modified = JSON.stringify(input);
modified = modifiedCollection.replace(/{\"key\":\"filekey\[(.*?)\]\",\"value\":\"(.*?)\",\"type\":\"text\"}/mg, '{"key":"\$1","src":"\$2","type": "file"}')
return JSON.parse(modified);
}
我还进行了调整,通过允许输入诸如filekey[file_url]
之类的密钥名称并将其转换为"key": "file_url"
来对密钥名称进行更多配置。