Python 3:JSON 不可序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36212905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:33:52  来源:igfitidea点击:

Python 3: Is not JSON serializable

pythonpython-3.x

提问by njha

TypeError: b'Pizza is a flatbread generally topped with tomato sauce and cheese and baked in an oven. It is commonly topped with a selection of meats, vegetables and condiments. The term was first recorded in the 10th century, in a Latin manuscript from Gaeta in Central Italy. The modern pizza was invented in Naples, Italy, and the dish and its variants have since become popular in many areas of the world.\nIn 2009, upon Italy\'s request, Neapolitan pizza was safeguarded in the European Union as a Traditional Speciality Guaranteed dish. The Associazione Verace Pizza Napoletana (the True Neapolitan Pizza Association) is a non-profit organization founded in 1984 with headquarters in Naples. It promotes and protects the "true Neapolitan pizza".\nPizza is sold fresh, frozen or in portions, and is a common fast food item in North America and the United Kingdom. Various types of ovens are used to cook them and many varieties exist. Several similar dishes are prepared from ingredients commonly used in pizza preparation, such as calzone and stromboli.' is not JSON serializable

I have a program that adds this into a JSON string, which works fine for most text strings - but not this one apparently. Can you tell why not, or how to fix it?

我有一个程序将它添加到 JSON 字符串中,它适用于大多数文本字符串 - 但显然不是这个。你能告诉为什么不,或者如何解决它?

回答by Amadan

This is not a string, but a byte sequence. JSON knows only how to handle Unicode strings, not byte sequences. Either transform into Unicode (json.dumps(x.decode("utf-8"))), or into an integer array (json.dumps(list(x))).

这不是字符串,而是字节序列。JSON 只知道如何处理 Unicode 字符串,而不知道如何处理字节序列。要么转换为 Unicode ( json.dumps(x.decode("utf-8"))),要么转换为整数数组 ( json.dumps(list(x)))。

回答by Andriy Ivaneyko

Consider installing and using simplejson, which can handle bytes strings in addition to unicode, to install it use command below:

考虑安装和使用simplejson,除了 unicode 之外,它还可以处理字节字符串,使用下面的命令安装它:

pip3 install simplejson

Usage in code:

代码中的用法:

import simplejson as json

json.dumps({b'name': b'dev'})