首页 > 解决方案 > 修复了 json.dumps 上的 python for 循环不打印提供的完整列表

问题描述

您好我正在尝试在 python 中使用 json.dumps 创建 json 代码。我有一个被读取并放入列表的 IP 地址列表。我正在尝试遍历 IP 列表并创建多个地址。我遇到的问题是它使用 for 循环的最后一个结果而不是完整列表来执行 json.dumps。

这是我的代码:

with open ('example_file.txt', 'r') as ip_list: #provide the path of the local file that stores the ip addresses
    ip_address = [line.rstrip() for line in ip_list] # Puts the ips in a list 

for each_ip in ip_address:
    gateway_dict = {'type': 'RANGE', 'value': (each_ip + '-' + each_ip)}
    json.dumps(gateway_dict)

print(gateway_dict)

示例文件.txt:

192.168.1.1
10.135.135.2
24.50.225.54

我希望 json 的结果是这种格式:

{'type': 'RANGE', 'value': '192.168.1.1-192.168.1.1'},
{'type': 'RANGE', 'value': '10.135.135.2-10.135.135.2'},
{'type': 'RANGE', 'value': '24.50.225.54-24.50.225.54'}

我得到的结果只是最后一个值的 json 转储:

{'type': 'RANGE', 'value': '24.50.225.54-24.50.225.54'}

标签: pythonjsonfor-loop

解决方案


由于相同的键,当前循环会覆盖循环的每次迭代中的值。相反,你可以有这样的东西:

 with open ('example_file.txt', 'r') as ip_list: #provide the path of the local file that stores the ip addresses
        ip_address = [line.rstrip() for line in ip_list] # Puts the ips in a list 

    gateway_dict = {}
    gateway_dict['record'] = [] # Doesn't have to be 'record' can be something more meaningful
    for each_ip in ip_address:
        gateway_dict['record'].append({
            'type': 'RANGE',
            'value': each_ip + '-' + each_ip
        })
        json.dumps(gateway_dict)

根据您说您需要的格式,您可能需要使用 json.dumps 命令。但这应该会给你你想要的输出:

for item in gateway_dict['record']:
    print(item)

推荐阅读