簡體   English   中英

如何在 python 中將多個 json 文件(來自網站的元數據)合並為一個 json 文件 dor EDA?

[英]How to merge multiple json files (metadata from website) into one json file dor EDA in python?

我正在處理 2 個混合 json 文件和收集的音頻文件夾(大約 400 個 json 文件),如下所示:

{
  "id":"c79c32e7-6665-4c5e-9458-d15930488263",
  "age":"34",
  "gender":"m",
  "healthStatus":"healthy",
  "audioFiles":[
    "1585940317337_sentence_healthy_m_34_c79c32e7-6665-4c5e-9458d15930488263.wav",
    "1585940317337_cough_healthy_m_34_c79c32e7-6665-4c5e-9458-d15930488263.wav",
    "1585940317337_breath_healthy_m_34_c79c32e7-6665-4c5e-9458d15930488263.wav"
  ]
}

我想檢索agegender和健康狀態並將它們合並到一個healthStatus文件中,以便在 python 中進行分析。

為此,我寫道:

from pathlib import Path
import json
data_folder = Path("/Users/jiani/Desktop/Voicemed/#ml/cough_classification-original_experiment/new_data/meta1")
read_files = glob.glob("data_folder/.json")

output_list = []

for f in read_files:
    with open(f, "rb") as infile:
        output_list.append(json.load(infile))

with open("merged_file.json", "w") as outfile:
    json.dump(output_list, outfile)

然后我打印了output_list ,但我得到了一個空的。 我已經閱讀了一些相關的解決方案,但我仍然無法得到答案。 有人可以幫助我嗎?

非常感謝。

嘗試這個:

from os import listdir
from os.path import isfile, join
import json

data_folder = "full/path/to/jsons"
files = [join(data_folder,f) for f in listdir(data_folder) if isfile(join(data_folder, f)) and f.endswith(".json")]

output_list = []
for file in files:
    with open(file, "r") as f:
        output_list.append({k:v for k,v in json.load(f).items() if k in ["age","gender","healthStatus"]})

with open("merged_file.json", "w") as outfile:
    json.dump(output_list, outfile)

暫無
暫無

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

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