使用 Python 将多个 JSON 文件合并为一个文件(流推特)
Merge multiple JSON files into one file by using Python (stream twitter)
我已经从推特上提取了数据。目前,数据在多个文件中,我无法将它们合并到一个文件中。
注意:所有文件均为 JSON 格式。
It has been suggested to work with glop
to compile JSON files
我按照我在一些关于合并 JSON 的教程中看到的使用 Python
编写此代码
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
我认为问题在于您的文件并不是真正的 json(或者更好的是,它们的结构为 jsonl)。您有两种处理方式:
- 您可以将每个文件作为文本文件读取并逐行合并它们
- 您可以将它们转换为 json(在文件的开头添加一个方括号,并在每个 json 元素的末尾添加一个逗号)。
试试这个问题,如果它能解决您的问题,请告诉我:
您也可以尝试以这种方式编辑您的代码:
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 元素。
我已经从推特上提取了数据。目前,数据在多个文件中,我无法将它们合并到一个文件中。
注意:所有文件均为 JSON 格式。
It has been suggested to work with glop
to compile JSON files
我按照我在一些关于合并 JSON 的教程中看到的使用 Python
编写此代码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
我认为问题在于您的文件并不是真正的 json(或者更好的是,它们的结构为 jsonl)。您有两种处理方式:
- 您可以将每个文件作为文本文件读取并逐行合并它们
- 您可以将它们转换为 json(在文件的开头添加一个方括号,并在每个 json 元素的末尾添加一个逗号)。
试试这个问题,如果它能解决您的问题,请告诉我:
您也可以尝试以这种方式编辑您的代码:
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 元素。