MySQL Decimal is not JSON serializable and case Analysis of inserting decimal number into 0
This article is to share with you about MySQL Decimal is not JSON serializable and the example analysis of inserting decimals into zero. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Using the web service built by Python, after reading the MySQL data at the backend, you need to serialize the data into a json string and return it to the frontend. But if the field of MySQL is of type decimal, you will have trouble serializing it into a json string. The following error will be reported
Raise TypeError (repr (o) + "is not JSON serializable")
TypeError: Decimal ('0') is not JSON serializable
HTTP/1.0 "500"
There are some solutions on the Internet, but if you are not so demanding about data precision, you can change the type of decimal field in MySQL to float,float type. You can serialize it directly. In this way, you can fix the problem by modifying only the database and not the code. Refer to the following figure. In addition, when setting the float type, be sure to set it after the decimal point, which can be set to 4, which means 4 decimal places. Otherwise, the default may be with 0 decimal places, which is not accurate. If your insert data is similar to '0.022', it becomes zero in the database.
It is recommended to use Navicat for MySQL to operate the database, this software is charged, it is easy to crack, of course, people are encouraged to use the genuine version. Right-click the name of the table, select "Design Table", and then you will see the above picture content, in which you can change the field type, length, increase the index and so on, which is much more convenient than statement operation.
The above is the example analysis of MySQL Decimal is not JSON serializable and the insertion of decimals into zero. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.