如何修复“OverflowError:编码字符串时不支持的UTF-8序列长度”?

5
在将Pandas数据框转换为JSON时出现以下错误:

OverflowError: 当编码字符串时,不支持UTF-8序列长度

这是代码:
        bytes_to_write = data.to_json(orient='records').encode()
        fs = s3fs.S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key)
        with fs.open(file, 'wb') as f:
            f.write(bytes_to_write)

当尝试将数据转换为json时,其中包含更多的utf-8编码。

如何解决这个问题?

1个回答

5
根据这个回答的建议,我使用了函数.to_json()default_handler参数来转换数据框。你可以在这里找到官方文档。
请注意要使用default_handler=str参数以避免上述错误。你可以在上面的文档中阅读详细信息。
dataframe.to_json('foo.json', default_handler=str) 

请不要忘记考虑函数可以以不同的方式输出 jsonorient='<option>' 参数指定了如下文档所述的方式:
orient: str
Indication of expected JSON string format.
...
The format of the JSON string:

- ‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
- ‘records’ : list like [{column -> value}, … , {column -> value}]
- ‘index’ : dict like {index -> {column -> value}}
- ‘columns’ : dict like {column -> {index -> value}}
- ‘values’ : just the values array
- ‘table’ : dict like {‘schema’: {schema}, ‘data’: {data}}

Describing the data, where data component is like orient='records'.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接