检查 object 并对所有匹配的 child 节点执行修改

Inspect an object and perform modifications on all matching child nodes

我正在处理一个大型 JSON 配置文件(顺便说一句,Postman/Newman API 请求的集合)并且需要在 [=50= 之前对此执行一些修改] 它在 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"

的children

2) 对于每个匹配的 child,修改它们的键和值如下:

// 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) 一旦完成,return整个修改object.

备注

我想避免对 JSON 进行字符串化,然后再对 运行 进行 Regex 替换,因为我认为这在未来会不太通用。但这似乎是目前最简单的方法:

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".

来允许对键名进行更多配置