Python 3: Is not JSON serializable

Question:

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?

Asked By: njha

||

Answers:

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))).

Answered By: Amadan

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

pip3 install simplejson

Usage in code:

import simplejson as json

json.dumps({b'name': b'dev'})
Answered By: Andriy Ivaneyko
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.