[英]How to merge two JSON file with pandas
我正在嘗試做一個合並2個json文件的python腳本,例如:
第一檔:students.json
{"John Smith":{"age":16, "id": 1}, ...., "Paul abercom":{"age":18, "id": 764}}
第二檔:teacher.json
{"Agathe Magesti":{"age":36, "id": 765}, ...., "Tom Ranliver":{"age":54, "id": 801}}
所以在第一次,為了不丟失任何信息,我修改文件以添加每個人的狀態:
{"John Smith":{"age":16, "id": 1, "status":"student"}, ...., "Paul abercom":{"age":18, "id": 764, "status":"student"}}
{"Agathe Magesti":{"age":36, "id": 765, "status":"teacher"}, ...., "Tom Ranliver":{"age":54, "id": 801, "status":"teacher"}}
為此,我做了以下代碼:
import pandas as pd
type_student = pd.read_json('student.json')
type_student.loc["status"] = "student"
type_student.to_json("testStudent.json")
type_teacher = pd.read_json('teacher.json')
type_teacher.loc["status"] = "teacher"
type_teacher.to_json("testTeacher.json")
with open("testStudent.json") as data_file:
data_student = json.load(data_file)
with open("testTeacher.json") as data_file:
data_teacher = json.load(data_file)
我想要做的是合並data_student和data_teacher並在json文件中打印生成的JSON,但我只能使用標准庫,pandas,numpy和scipy。
經過一些測試,我意識到一些老師也是學生,這可能是合並的問題。
在轉換為JSON之前,您應該連接兩個數據框:
pd.concat([data_teacher, data_student], axis=1).to_json()
看起來你的JSON文件包含“對象”作為頂級結構。 這些映射到Python詞典。 所以使用Python應該很容易。 只需用第二個字典更新第一個字典。
import json
with open("mel1.json") as fo:
data1 = json.load(fo)
with open("mel2.json") as fo:
data2 = json.load(fo)
data1.update(data2)
with open("melout.json", "w") as fo:
json.dump(data1, fo)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.