簡體   English   中英

如何在 Python 中加入(合並)幾個 JSON 文件

[英]How to join (merge) several JSON files in Python

新來的,開始在 python 上學習編程,我目前正在編寫一個腳本來加入幾個 JSON 文件(通過另一個 API CALL 腳本生成)。

我已經嘗試了這里提供的幾種解決方案(熊貓、合並等),其中一些有效(它們實際上加入了文件),但生成的文件格式不正確或項目不按順序排列。

我試圖加入/合並的文件是: 2 JSON 文件

我真的需要加入/合並比這 2 個更多,但我想首先確保它們正確加入,然后我可以編寫一些代碼來加入/合並 rest(它們都具有與這 2 個相同的結構)。

謝謝你的幫助。

編輯:JSON 文件信息(不完整):json 文件 1:

{“0”:{“id_property”:“0001”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1 ", "卧室": "1",

“1”:{“id_property”:“0002”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1” , "卧室": "1",

“2”:{“id_property”:“0003”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1” ,“卧室”:“1”,},“狀態”:“成功”,“總數”:63 }

json 文件 2:

{“0”:{“id_property”:“0004”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1 ", "卧室": "1",

“1”:{“id_property”:“0005”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1” , "卧室": "1",

“2”:{“id_property”:“0006”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1” ,“卧室”:“1”,},“狀態”:“成功”,“總數”:66 }

我想加入/合並它們並最終得到

合並 json:

{“0”:{“id_property”:“0001”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1 ", "卧室": "1",

“1”:{“id_property”:“0002”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1” , "卧室": "1",

“2”:{“id_property”:“0003”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1” ,“卧室”:“1”,“3”:{“id_property”:“0004”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用", "浴室": "1", "卧室": "1",

“4”:{“id_property”:“0005”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1” , "卧室": "1",

“5”:{“id_property”:“0006”“地址”:“PH COLORES DE BELLA VISTA,BELLA VISTA”,“區域”:“48”,“availability_label”:“可用”,“浴室”:“1” , "卧室": "1", }, }

首先加載文本文件並轉換為 python 字典:

import json

with open("file1.json"), "r") as f1:
    d1 = json.loads(f1.read())
with open("file2.json"), "r") as f2:
    d2 = json.loads(f2.read())

然后加入他們:

d1.update(d2)

d1 是結果,但如果兩個字典中存在相同的鍵,則 d2 會覆蓋 d1。

生成的 json 一團糟,(對我來說)要完成我想做的事情需要大量的工作和時間。 So i ended up taking a different approach, the system where i was pulling the json data from also offers a csv file via web, so i wrote a script with the use of selenium and chromedriver to log into my account and request the csv file. 然后另一個腳本登錄到我的 email 並下載隨附的 csv 文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM