python - 使用 json_modify.py 更改 JSON 键名称

标签 python json python-3.x ansible ansible-2.x

如何使用 json_modify.py 更改 JSON 键名称?

我有以下数组,我想将 public_ip_address 更改为 public_ip_address_name

                                "ip_configurations": [
                                    {
                                        "application_gateway_backend_address_pools": null,
                                        "application_security_groups": null,
                                        "load_balancer_backend_address_pools": null,
                                        "name": "Ubuntu915",
                                        "primary": true,
                                        "private_ip_address": "10.0.0.5",
                                        "private_ip_allocation_method": "Dynamic",
                                        "public_ip_address": "/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/publicIPAddresses/Ubuntu-915-test",
                                        "public_ip_allocation_method": "Dynamic"
                                    }
                                ],

这是我如何使用 json_modify 的示例,但我不确定如何更改 key 。

  - json_modify:
      data: "{{ azure_network_interface_info }}"
      pointer: "/networkinterfaces/0/ip_configurations/0"
      action: update
      update: { "public_ip_address": "testing" }
    register: azure_network_interface_info_modified 

以下是 azure_network_interface_info 的事实:

        {
            "hosts": {
                "localhost": {
                    "_ansible_no_log": null,
                    "action": "azure_rm_networkinterface_info",
                    "changed": false,
                    "invocation": {
                        "module_args": {
                            "ad_user": null,
                            "adfs_authority_url": null,
                            "api_profile": "latest",
                            "auth_source": "auto",
                            "cert_validation_mode": null,
                            "client_id": null,
                            "cloud_environment": "AzureCloud",
                            "log_mode": null,
                            "log_path": null,
                            "name": "Ubuntu915",
                            "password": null,
                            "profile": null,
                            "resource_group": "cloud-shell-storage-centralindia",
                            "secret": null,
                            "subscription_id": null,
                            "tags": null,
                            "tenant": null
                        }
                    },
                    "networkinterfaces": [
                        {
                            "dns_servers": [],
                            "dns_settings": {
                                "applied_dns_servers": [],
                                "dns_servers": [],
                                "internal_dns_name_label": null,
                                "internal_fqdn": null
                            },
                            "enable_accelerated_networking": false,
                            "enable_ip_forwarding": false,
                            "id": "/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/networkInterfaces/Ubuntu915",
                            "ip_configurations": [
                                {
                                    "application_gateway_backend_address_pools": null,
                                    "application_security_groups": null,
                                    "load_balancer_backend_address_pools": null,
                                    "name": "Ubuntu915",
                                    "primary": true,
                                    "private_ip_address": "10.0.0.5",
                                    "private_ip_allocation_method": "Dynamic",
                                    "public_ip_address": "/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/publicIPAddresses/Ubuntu-915-test",
                                    "public_ip_allocation_method": null
                                }
                            ],
                            "location": "eastus",
                            "mac_address": "00-0D-3A-8C-CF-8C",
                            "name": "Ubuntu915",
                            "provisioning_state": "Succeeded",
                            "resource_group": "cloud-shell-storage-centralindia",
                            "security_group": "/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/networkSecurityGroups/testing_testing_temp_123",
                            "subnet": "default",
                            "tags": null,
                            "virtual_network": {
                                "name": "testing-vm_group-vnet",
                                "resource_group": "testing-vm_group"
                            }
                        }
                    ]
                }
            },
            "task": {
                "duration": {
                    "end": "2022-07-25T16:39:01.551871Z",
                    "start": "2022-07-25T16:38:58.618111Z"
                },
                "id": "0242ac11-0002-08f0-de66-00000000000a",
                "name": "Get facts for one network interface"
            }
        },

最佳答案

好的,我找到了一个解决方案,就是修改库文件夹中的模块: 我添加了一个新功能renamekey,旧 key 的内容会自动添加到新 key

from ansible.module_utils.basic import AnsibleModule

import json

try:
    import jsonpointer
except ImportError:
    jsonpointer = None


def main():
    module = AnsibleModule(
        argument_spec=dict(
            data=dict(required=True, type='dict'),
            pointer=dict(required=True),
            action=dict(required=True,
                        choices=['append', 'extend', 'update', 'renamekey']),
            update=dict(type='dict'),
            extend=dict(type='list'),
            append=dict(),
            renamekey=dict(type='list'),
        ),
        supports_check_mode=True,
    )

    if jsonpointer is None:
        module.fail_json(msg='jsonpointer module is not available')

    action = module.params['action']
    data = module.params['data']
    pointer = module.params['pointer']

    if isinstance(data, str):
        data = json.loads(str)

    try:
        res = jsonpointer.resolve_pointer(data, pointer)
    except jsonpointer.JsonPointerException as err:
        module.fail_json(msg=str(err))


    if action == 'append':
        res.append(module.params['append'])
    if action == 'extend':
        res.extend(module.params['extend'])
    elif action == 'update':
        res.update(module.params['update'])
    elif action == 'renamekey':
        oldkey = module.params['renamekey'][0]
        newkey = module.params['renamekey'][1]
        value = res[oldkey]  #get the value of oldkey
        res.pop(oldkey)      #delete the oldkey
        res.update({module.params['renamekey'][1]: value}) #add newkey with value saved

    module.exit_json(changed=True,
                     result=data)


if __name__ == '__main__':
    main()

要测试的剧本:

- json_modify:
    data: "{{ azure_network_interface_info }}"
    pointer: "/networkinterfaces/0/ip_configurations/0"
    action: renamekey
    renamekey: ["public_ip_address", "public_ip_address_name"] #[oldkey, newkey]
  register: result

结果:

                        "ip_configurations": [
                            {
                                "application_gateway_backend_address_pools": null,
                                "application_security_groups": null,
                                "load_balancer_backend_address_pools": null,
                                "name": "Ubuntu915",
                                "primary": true,
                                "private_ip_address": "10.0.0.5",
                                "private_ip_allocation_method": "Dynamic",
                                "public_ip_address_name": "/subscriptions/123456/resourceGroups/test-rg/providers/Microsoft.Network/publicIPAddresses/Ubuntu915-publicIp",
                                "public_ip_allocation_method": null
                            }

关于python - 使用 json_modify.py 更改 JSON 键名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73109618/

相关文章:

python - 如何计算另一个列表中列表(作为 pandas 列)中的匹配元素的数量

python - 在 Python 中使用 os.stat() 结果时如何忽略隐藏文件?

for-loop - 对于列表,除非在 python 中为空

python - Django:类型转换抽象模型

Python:在命令提示符下一一打印字母

javascript - Undefined is not an object (evaluating 'React.PropTypes.Number') 错误

python - 如何在 Pycharm 的调试 session 中断期间向 python 类/对象添加方法?

python - 从 Excel 电子表格中提取值

javascript - 如何使用 jQuery.getJSON() 读取远程 JSON 文件?

python - 类型错误 : Object of type X is not JSON serializable