【问题标题】:Merge multiple JSON files into one file by using Python (stream twitter)使用 Python (stream twitter) 将多个 JSON 文件合并为一个文件
【发布时间】:2021-02-02 11:43:56
【问题描述】:

我已从 Twitter 中提取数据。目前,数据在多个文件中,我无法将其合并到一个文件中。

注意:所有文件均为 JSON 格式。

我使用的代码是herehere

It has been suggestedglop to compile JSON files 合作

我编写了这段代码,正如我在一些关于使用 Python 合并 JSON 的教程中看到的那样

from glob import glob 
import json
import pandas as pd

with open('Desktop/json/finalmerge.json', 'w') as f: 
    for fname in glob('Desktop/json/*.json'): # Reads all json from the current directory 
        with open(fname) as j: 
            f.write(str(j.read())) 
            f.write('\n') 
            

我成功合并了所有文件,现在文件是 finalmerge.json。

现在我按照几个线程中的建议使用了这个:


df_lines = pd.read_json('finalmerge.json', lines=True)
df_lines


1000000*23 columns 

Then, what I should do to make each feature in separate columns?



I'm not sure why what's wrong with JSON files, I checked the file that I merge and I found it's not valid as JSON file? what I should do to make this as a data frame?

The reason I am asking this is that I have very basic python knowledge and all the answers to similar questions that I have found are way more complicated than I can understand. Please help this new python user to convert multiple Json fils to one JSON file.

Thank you

【问题讨论】:

    标签: python json api twitter


    【解决方案1】:

    我认为问题在于您的文件不是真正的 json(或者更好的是,它们的结构为 jsonl )。您有两种处理方式:

    1. 您可以将每个文件作为文本文件读取并逐行合并
    2. 您可以将它们转换为 json(在文件的开头添加一个方括号,在每个 json 元素的末尾添加一个逗号)。

    尝试关注这个问题,如果它解决了您的问题,请告诉我:Loading JSONL file as JSON objects

    您也可以尝试以这种方式编辑您的代码:

    with open('finalmerge.json', 'w') as f:
        for fname in glob('Desktop/json/*.json'): 
            with open(fname) as j:
                f.write(str(j.read()))
                f.write('\n')
    

    每一行都是不同的 json 元素。

    【讨论】:

    • 它可以工作,但只适用于一个文件,所以我不知道如何让它同时适用于多个文件?
    • 我认为最简单的方法是这样的: from glob import glob with open('finalmerge.json', 'w') as f: for fname in glob('Desktop/json/* .json'): # 从当前目录读取所有 json 文件 open(fname) as j: f.write(str(j.read())) f.write('\n') 我会写在我的主目录回答
    • 谢谢,生成了合并文件,但它真的很大,现在如果我想将它转换为熊猫作为数据框,是否有一个具体的指令可以正确执行,因为我不知道这个jsonl .其次,我如何验证 JSON 文件。由于它的大小,有一种方法可以让我仔细检查 panda 中的数据框是否不会被拒绝文件
    • 在 pandas 文档中,您可以在读取 json 文件时找到 lines 选项。 pandas.pydata.org/pandas-docs/stable/reference/api/…检查生成的文件是否正常的最简单方法就是快速滚动它,看看是否有一些奇怪的行
    • 我意识到我合并的文件不是有效的 JSON 文件。我将在我的主要问题中写下这个。
    猜你喜欢
    • 2015-05-13
    • 2020-10-16
    • 1970-01-01
    • 2021-08-13
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多