Solution to json object conversion error in python

Source: Internet
Author: User
Today, I encountered a problem in using json conversion in python: receiving a post json string: s {& amp; quot; username & amp; amp; quot;: & amp; quot; admin & amp; amp; quot;, & amp; quot; password & amp; quot ;: today, I encountered a problem in using json conversion in python:

Receives a post json string:

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 "
 
  ", line 1, in 
  
     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!


Think twice about it. After debugging, it is found that the single quotation mark (') is used to represent the string "'" by default in python "'"

Therefore, after a string is used, python converts double quotation marks into single quotation marks.

>>> S = {"username": "admin", "password": "password", "tenantid ":""}

>>> Print s

{'Username': 'admin', 'password': 'Password', 'tenantid ':''}

Json does not support single quotes.


You can use the following method to convert

Json_string = json. dumps (s)

Python_obj = json. loads (json_string)


OK, problem solving

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.