第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何拆分 JSON 文檔?

如何拆分 JSON 文檔?

人到中年有點甜 2021-11-09 20:26:59
我有一個包含許多文檔的 JSON 文件。每個文檔都是來自一個采購訂單的數(shù)據(jù)。我從云采購訂單系統(tǒng)上的 Web 服務(wù)獲取文件。我需要將這些文檔中的每一個加載到 Oracle 數(shù)據(jù)庫中的單獨記錄中。我已經(jīng)使用 Oracle 的外部表功能對 JSON 文檔的其他文件執(zhí)行了此操作,并且已經(jīng)奏效。但是,其他文件在每個 JSON 文檔之間都有一個 crlf。我從 Web 服務(wù)獲得的文件是一個包含許多 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)但是當(dāng)我嘗試解決方案時,出現(xiàn)如下錯誤:[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貢獻(xiàn)1864條經(jīng)驗 獲得超6個贊

我認(rèn)為這會做你想做的。在json_obj_list返回的形式j(luò)son.load()實際上是一個Python字典,所以你需要重復(fù)的值json_obj_list['data']。為了使代碼對現(xiàn)有變量名稱保持合理,我將其修改為直接從返回的字典中檢索 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)


查看完整回答
反對 回復(fù) 2021-11-09
  • 1 回答
  • 0 關(guān)注
  • 299 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號