Solution to json object conversion error in python

高洛峰
Release: 2016-10-18 14:21:20
Original
1755 people have browsed it

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
>>>
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template