【问题标题】:Python 3: Is not JSON serializablePython 3:不是 JSON 可序列化的
【发布时间】:2016-03-25 01:56:05
【问题描述】:
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

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

【问题讨论】:

  • string = string.decode('utf-8').

标签: python python-3.x


【解决方案1】:

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

【讨论】:

  • @RickyLevi:首先,只要所有键都是字符串(或者像数字一样干净地字符串化),转储 dict 的 dict 就没有问题。其次,请提出一个新问题(minimal reproducible example);这个答案回答了 OP 提出的问题。
【解决方案2】:

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

pip3 install simplejson

代码中的用法:

import simplejson as json

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

【讨论】:

  • 将我的 python2 脚本升级到 python3 时出现此错误。似乎etree.tostring(...) 的输出现在是一个字节字符串,并将其传递给request.post(...json=x...) 开始失败。这个答案对我有用。
  • 在将一些 py2 移植到 py3 时,我遇到了一个深度嵌套的字节对象结构(嵌套字典和嵌套数组)。遍历所有树并将所有字节对象转换为字符串对象效率低下、麻烦且丑陋。 Simplejson 完美地做到了这一点。
猜你喜欢
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2015-01-07
相关资源
最近更新 更多