为了账号安全,请及时绑定邮箱和手机立即绑定

如何拆分 JSON 文档?

如何拆分 JSON 文档?

人到中年有点甜 2021-11-09 20:26:59
我有一个包含许多文档的 JSON 文件。每个文档都是来自一个采购订单的数据。我从云采购订单系统上的 Web 服务获取文件。我需要将这些文档中的每一个加载到 Oracle 数据库中的单独记录中。我已经使用 Oracle 的外部表功能对 JSON 文档的其他文件执行了此操作,并且已经奏效。但是,其他文件在每个 JSON 文档之间都有一个 crlf。我从 Web 服务获得的文件是一个包含许多 PO 的文档,采购订单之间没有 crlf。我在这里找到了问答:How to split json into multiple files per document。显示为解决方案的代码是import jsonin_file_path='path/to/file.json' # Change me!with open(in_file_path,'r') as in_json_file:    # Read the file and convert it to a dictionary    json_obj_list = json.load(in_json_file)    for json_obj in json_obj_list:        filename=json_obj['_id']+'.json'        with open(filename, 'w') as out_json_file:            # Save each obj to their respective filepath            # with pretty formatting thanks to `indent=4`            json.dump(json_obj, out_json_file, indent=4)但是当我尝试解决方案时,出现如下错误:[oracle@localhost gk]$ python36 split.pyTraceback (most recent call last):  File "split.py", line 11, in <module>    filename=json_obj['_id']+'.json'TypeError: string indices must be integers我的 JSON 文件如下所示:{    "data": [        {            "number": "PB510698",            "uuid": "9cc06f21c1194038b137cec51b02606b"        },        etc ...    ]}以多个文档(子文档?)开头 {"number":"PB510698","uuid"任何想法为什么另一篇文章中的代码不起作用?
查看完整描述

1 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

我认为这会做你想做的。在json_obj_list返回的形式json.load()实际上是一个Python字典,所以你需要重复的值json_obj_list['data']。为了使代码对现有变量名称保持合理,我将其修改为直接从返回的字典中检索 JSON 对象列表,json.load()如下所示:


json_obj_list = json.load(in_json_file)['data']

这是完整的代码:


import json



in_file_path = 'testfile.json'


with open(in_file_path,'r') as in_json_file:


    # Read the file and get the list from the dictionary.

    json_obj_list = json.load(in_json_file)['data']


    for json_obj in json_obj_list:

        filename = json_obj['number']+'.json'  # Changed this, too, per comment by OP.

        print('creating file:', filename)

        with open(filename, 'w') as out_json_file:

            # Save each obj to their respective filepath

            # with pretty formatting thanks to `indent=4`

            json.dump(json_obj, out_json_file, indent=4)


查看完整回答
反对 回复 2021-11-09
  • 1 回答
  • 0 关注
  • 246 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信