用JSON中的动态值替换键

时间:2019-11-19 05:18:24

标签: javascript json servicenow

在下面的JSON中,我想用下面的语句从表单中获取的Alliance和env的动态值替换keys xyz和abc,用下面的直接对象名称替换引号中的abc字,这给了我一个错误。有什么办法做到这一点?

var env = g_form.getValue('vpc_environment_type');
var alliance = g_form.getValue('alliance_business_unit');
var team = g_form.getVal`enter code here`ue('alliance_segment_team_name_df_ingestion');
var project = g_form.getValue('project_name_gcp_df_ingestion_npe');

var requestBody =   {
  "format_version": "0.2.19",
  "alliances": {
    "xyz": {
      "environments": {
        "abc": {
          "teams": {
            "dna": {
              "action": "edit",
              "team": "dna",
              "projects": {
                "xxxx": {
                  "project": "xxxxx",
                  "cost_center": "0",
                  "custom_iam_policies": [],
                  "iam": {
                    "dev_group_email_name": "123",
                    "view_group_email_name": "456",
                    "sre_admin_group_email_name": "789"
                  },
                  "allowed_apis": [
                    "123",
                    "123"
                  ],
                  "networks": {
                    "xxxxx": {
                      "flags": [
                        "VM"
                      ],
                      "region": "123,
                      "preferred-suffix" : "123"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
};

requestBody = new global.JSON().encode(requestBody);
console.log(requestBody);

2 个答案:

答案 0 :(得分:0)

尝试类似这样的方法。请注意,您不能只是在JavaScript对象中重命名键,您需要添加具有新名称的新键,并在不需要时删除旧键。另外请注意,如果数据发生突变,则删除旧键时可能会删除新键中的值。

var alliance = g_form.getValue('alliance_business_unit');
requestBody.alliances[alliance] =  requestBody.alliances.xyz;

这将在联盟中添加新密钥,其密钥名称是从g_form.getValue('alliance_business_unit');返回的密钥名称

类似地也用于env。

动态分配是这样完成的

object[variable] = value; 

如果您的变量具有值测试,那么您将有一个像这样的对象

{test: 'your value' }

答案 1 :(得分:0)

字符串化>替换>转换为JSON

您需要用所需的键替换字符串: Dynamic1 Dynamic2

requestBody = JSON.parse(JSON.stringify(requestBody).replace("\"xyz\"","\"Dynamic1\"").replace("\"abc\"","\"Dynamic2\""));

更新: 您可以通过这种方式将变量用作键。

var newKey1 = "DynamicKey1";
requestBody.alliances[newKey1] = requestBody.alliances.xyz;

var newKey2 = "DynamicKey2";
requestBody.alliances[newKey1].environments[newKey2] = requestBody.alliances[newKey1].environments.abc;