python - 修复了 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'}
解决方案
由于相同的键,当前循环会覆盖循环的每次迭代中的值。相反,你可以有这样的东西:
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)
推荐阅读
- asp.net-core - 无法在 ASP.NET Core 3.1 中从 InProcess 切换到 OutOfProcess ASP.NET Core 托管模式
- html - Laravel 生成的电子邮件未正确格式化 HTML
- javascript - 如何更正 LeaderLine 中的倒置标签?
- docker - .net core 3.1 应用程序不会通过 docker 在浏览器上运行
- php - PHP mysqli 区分大小写的查询,但在 phpmyadmin 中运行时不区分大小写
- c# - 如果后台方法需要 UI,则任务不起作用:调用线程必须是 STA,因为许多 UI 组件都需要这个
- r - 如果 Shiny 应用程序中没有互联网连接,则消息(警报)
- angular - 如何在 ag 网格范围内获取组件变量
- angular - 如何使用 now ziet 从一个 url 提供多个构建,以支持 angular i18n
- excel - 在主题行中查找具有特定文本的电子邮件项目 - 优化