【问题标题】:list of json files into jsonL file using Python使用 Python 将 json 文件列表转换为 jsonL 文件
【发布时间】:2020-05-29 17:44:52
【问题描述】:

我有一个包含大量 json 文件的目录。现在我希望 python 将它们全部读入并创建一个 jsonl 输出文件。

这是一个类似的帖子 (Python conversion from JSON to JSONL),但与这篇帖子相比,我的问题的出发点是先读取 jsons 以创建 python 对象,然后再将它们转换为 jsonl。

【问题讨论】:

    标签: python json


    【解决方案1】:

    以下是您如何从 python 目录中读取 json 文件,然后将加载的 json 文件输出到单个 jsonl 文件中:

    import os, json
    import pandas as pd
    
    directory = '/Path/To/Your/Json/Directory'  #Specify your json directory path here
    
    json_list=[]    #Initiate a new blank list for storing json data in list format
    for dirpath, subdirs, files in os.walk(directory):
        print(dirpath)
        print(filename)
        print(file)
        for file in files:
            if file.endswith(".json"):
                with open(os.path.join(dirpath, file)) as json_file: 
                    data = json.load(json_file) 
                    json_list.append(data)
    
    #Now, output the list of json data into a single jsonl file
    with open('output.jsonl', 'w') as outfile:
        for entry in json_list:
            json.dump(entry, outfile)
            outfile.write('\n')
    

    【讨论】:

      猜你喜欢
      • 2016-05-14
      • 2021-08-24
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 2021-08-23
      • 2021-07-05
      相关资源
      最近更新 更多