在解析过程中忽略一些 json 个文件
Ignore some json files during parsing
我有以下代码,它从目录中读取一些 JSON
文件,并在一些预处理后 returns 它们。但是,其中一些是字典,因此它们没有所需的列。结果,我收回这个错误
KeyError: "None of [Index(['aaa', 'xxx'], dtype='object')] are in the [columns]"]
如何忽略它们并继续其他 JSON
文件?也许是 try-except 程序?
import os, json
import pandas as pd
path_to_json = 'C:/Users/aaa/Desktop/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
def func(s):
try:
return eval(s)
except:
return dict()
list_of_df=[]
for i in range(len(json_files)):
file_name = json_files[i]
df = pd.read_json(file_name, lines=True)
df= df[['columnx']]
df = df['columnx'].apply(func)
df=pd.json_normalize(df)
df=pd.DataFrame(df[["xxx", "aaa"]])
list_of_df.append(df)
df=pd.concat(list_of_df)
df = df[['Index','xxx', 'aaa']]
df.head()
您必须在遍历 json 文件的 for 循环中添加 try-except 块。
我有以下代码,它从目录中读取一些 JSON
文件,并在一些预处理后 returns 它们。但是,其中一些是字典,因此它们没有所需的列。结果,我收回这个错误
KeyError: "None of [Index(['aaa', 'xxx'], dtype='object')] are in the [columns]"]
如何忽略它们并继续其他 JSON
文件?也许是 try-except 程序?
import os, json
import pandas as pd
path_to_json = 'C:/Users/aaa/Desktop/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
def func(s):
try:
return eval(s)
except:
return dict()
list_of_df=[]
for i in range(len(json_files)):
file_name = json_files[i]
df = pd.read_json(file_name, lines=True)
df= df[['columnx']]
df = df['columnx'].apply(func)
df=pd.json_normalize(df)
df=pd.DataFrame(df[["xxx", "aaa"]])
list_of_df.append(df)
df=pd.concat(list_of_df)
df = df[['Index','xxx', 'aaa']]
df.head()
您必须在遍历 json 文件的 for 循环中添加 try-except 块。