Home > Article > Backend Development > Solution to json object conversion error in python
I encountered a problem today when using json conversion in python:
Receive the json string of a post:
s={"username":"admin","password":"password","tenantid":" "}
Use the json library that comes with python
import json >>> a=json.loads(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/json/__init__.py", line 326, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer >>>
Error!
I am puzzled. After debugging, it was finally discovered that single quotes are used by default in python to represent the string "'"
So when using string symbols, python will convert double quotes into single quotes
>>> s={"username" :"admin","password":"password","tenantid":""}
>>> print s
{'username': 'admin', 'password': 'password', 'tenantid': ''}
And json does not support single quotes.
can be converted using the following method
json_string=json.dumps(s)
python_obj=json.loads(json_string)
ok, problem solved