根据您提供的错误信息,问题发生在调用 df.to_json(orient='records', lines=True) 时。具体的错误是 OverflowError: Overlong 3 byte UTF-8 sequence detected when encoding string,这通常与 ujson 库处理某些字符编码的问题有关。
pandas 的 to_json 方法在内部可能使用了 ujson 来加速 JSON 的序列化,但 ujson 有时会在处理包含特殊或无效 UTF-8 字符的数据时抛出类似的错误。
为了解决这个问题,您可以尝试以下方法:
方法1:避免使用 df.to_json,改用标准的 json 模块
您可以先将 DataFrame 转换为字典列表,然后使用标准的 json 模块进行序列化。这可以避免使用可能导致问题的 ujson,并让您更好地控制序列化过程。
请修改您的代码如下:
python Copy code
import os
import pandas as pd
import json
def convert_parquet_to_json(directory_path):
# 遍历目录树
for root, dirs, files in os.walk(directory_path):
for filename in files:
if filename.endswith('.parquet'):
parquet_file_path = os.path.join(root, filename)
# 读取Parquet文件
df = pd.read_parquet(parquet_file_path)
# 将DataFrame转换为字典列表
json_data = df.to_dict(orient='records')
# 生成JSON文件路径
json_file_path = os.path.join(root, filename.replace('.parquet', '.json'))
# 将JSON数据写入文件
with open(json_file_path, 'w', encoding='utf-8') as f:
for item in json_data:
f.write(json.dumps(item, ensure_ascii=False) + '\n')
print(f"Parquet file '{parquet_file_path}' has been converted to JSON file '{json_file_path}'")
# 示例调用
directory_path = '/root/autodl-tmp/OlympiadBench/OlympiadBench'
convert_parquet_to_json(directory_path)
在这个修改后的代码中,我们:
使用 df.to_dict(orient='records') 将 DataFrame 转换为字典列表,而不是使用 df.to_json。
使用标准的 json.dumps 方法进行序列化,设置 ensure_ascii=False 以正确处理 Unicode 字符。
方法2:强制 pandas 使用内置的 json 模块
如果您更喜欢继续使用 df.to_json,可以尝试强制 pandas 使用内置的 json 模块,而不是 ujson。这可以通过卸载 ujson 库来实现:
bash Copy code
pip uninstall ujson
或者,您可以在更高版本的 pandas 中使用 json_backend 参数:
python Copy code
json_str = df.to_json(orient='records', lines=True, force_ascii=False, json_backend='json')
但需要注意的是,json_backend 参数可能在您的 pandas 版本中不可用。
方法3:处理 DataFrame 中的无效字符
如果上述方法仍然无法解决问题,可能需要检查 DataFrame 中的数据,处理可能存在的无效或损坏的字符。您可以在转换前清理数据,例如:
python Copy code
for col in df.columns:
if df[col].dtype == object:
df[col] = df[col].astype(str).apply(lambda x: x.encode('utf-8', 'replace').decode('utf-8'))
这将确保所有的字符串列都被正确编码,替换无法编码的字符。
总结
最直接的解决方案是使用方法1,避免使用可能导致问题的 df.to_json,直接使用 df.to_dict 并使用标准的 json 库进行序列化。
希望这些建议能帮助您解决问题!
English Summary:
The error occurs due to ujson not handling certain UTF-8 characters properly during serialization in df.to_json. By converting the DataFrame to a list of dictionaries using df.to_dict(orient='records') and then using the standard json.dumps, you can avoid the issue caused by ujson. This method gives you better control over the serialization process and correctly handles Unicode characters.
解决方案:修改代码,使用 df.to_dict 并用标准的 json 模块进行序列化
python Copy code
# ...
df = pd.read_parquet(parquet_file_path)
json_data = df.to_dict(orient='records')
with open(json_file_path, 'w', encoding='utf-8') as f:
for item in json_data:
f.write(json.dumps(item, ensure_ascii=False) + '\n')
# ...