Python

DataFrame to json utf8 한글

Dongmin Jang 2022. 1. 7. 16:34

실패

jsonData = json.loads(df.to_json(orient="records"))

with open("data.json", "w", encoding='utf8') as json_file:
    json.dump(jsonData, json_file, indent=4)

with open("data.json", "w") as json_file:
    json.dump(jsonData, json_file, indent=4)

성공

pandas DataFrame to json file UTF-8 한글

df = pd.DataFrame()

jsonData = json.loads(df.to_json(orient="records"))

with open("data.json", "w", encoding='utf8') as json_file:
    json.dump(jsonData, json_file, indent=4, ensure_ascii=False)

null인 요소 제거

df = pd.DataFrame()

# file.write()
parsedData = json.dumps([row.dropna().to_dict() for index,row in df.iterrows()], indent=4, ensure_ascii=False)
with open("data.json", "w", encoding='utf8') as json_file:
    json_file.write(parsedData)

# json.dump()
with open("data.json", "w", encoding='utf8') as json_file:
    json.dump([row.dropna().to_dict() for index,row in df.iterrows()], json_file, indent=4, ensure_ascii=False)