python - 如何重新格式化 JSON 文件以包含数组
问题描述
我有一个json_file
包含 2 条记录的 json 文件:
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null}
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
如何使用 python 重新格式化文件以使其具有一个这样的数组:
{
"foo" : [
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
]
}
解决方案
由于您的 json 文件无效,我们需要逐行读取:
import json
input_file = """{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null}
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}"""
output_dict = dict()
output_dict['foo'] = list()
for line in input_file.split('\n'):
json_line = json.loads(line)
output_dict['foo'].append(json_line)
print(json.dumps(output_dict, indent=2))
然后我们创建您想要的数据结构,并将每行 json 附加到该数据结构。
推荐阅读
- java - 如何实现与中间一个类的关联——Person、owns、Car
- logging - junit -- 在没有模拟的情况下验证 LOGGER
- json - vue 中的对象动作
- ruby-on-rails-5 - 为什么 ActionCable 在找不到登录用户时不断尝试升级连接
- angular - 离子搜索栏 - 搜索结果优先级
- excel - 在 Excel 中显示带有重复数字的文本(每个项目显示 2 次)
- swift - 如何使用 Core Image 将色调颜色应用于 UIImage
- php - Laravel - 如何在 Maatwebsite excel 中使用 foreach 创建标题行
- angular - 角度反应形式的自定义组件中的验证不起作用
- java - Java 错误:二元运算符 '!=' 的操作数类型错误