I'm trying to write a pandas DataFrame containing unicode to json, but the built in .to_json function escapes the characters. How do I fix this?

Example:

import pandas as pd
df = pd.DataFrame([['τ', 'a', 1], ['π', 'b', 2]])
df.to_json('df.json')

这提供了:

{"0":{"0":"\u03c4","1":"\u03c0"},"1":{"0":"a","1":"b"},"2":{"0":1,"1":2}}

Which differs from the desired result:

{"0":{"0":"τ","1":"π"},"1":{"0":"a","1":"b"},"2":{"0":1,"1":2}}


I have tried adding the force_ascii=False argument:
import pandas as pd
df = pd.DataFrame([['τ', 'a', 1], ['π', 'b', 2]])
df.to_json('df.json', force_ascii=False)

但这会产生以下错误:

UnicodeEncodeError: 'charmap' codec can't encode character '\u03c4' in position 11: character maps to <undefined>


I'm using WinPython 3.4.4.2 64bit with pandas 0.18.0

推荐答案

Opening a file with the encoding set to utf-8, and then passing that file to the .to_json function fixes the problem:

with open('df.json', 'w', encoding='utf-8') as file:
    df.to_json(file, force_ascii=False)

给出正确的:

{"0":{"0":"τ","1":"π"},"1":{"0":"a","1":"b"},"2":{"0":1,"1":2}}

Note: it does still require the force_ascii=False argument.

Json相关问答推荐

从json数组中删除特定元素

我发现GoFr响应总是包含在数据字段中,如何返回自定义响应?

使用自定义类型在Golang中解析JSON数组

在linux控制台中解析json字符串的最简单方法是什么?

交换键和数组值,将旧键转换为新数组值,使用 jq

将 std::可选值存储到 json 文件 C++

VSCode 为 python 文件添加标尺,但不为 C 文件添加标尺.为什么?

PowerShell - 将 json 添加到文件内容

如何使用nifi从json文件中过滤属性

使用 jq 将消息转换为数组

JOLT JSON 将值从一对多转换为一对一

将 colly 包输出文本添加到 golang 中的映射

通过一个序列化器更新多个模型数据

使用 JQ 从文件中删除重复的 JSON 块

将 JSON 读取到 pandas 数据框 - ValueError:将 dicts 与非系列混合可能会导致排序不明确

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

JSON 到 JSON 转换器

如何向(JSON)对象的原型添加方法?

PHP json_encode json_decode UTF-8

使用 JavaScriptSerializer() 反序列化 JSON 文件