Python JSON module usage examples

Source: Internet
Author: User
JSON is actually a string representation of a Python dictionary, but a dictionary cannot be passed directly as a complex object, so it needs to be converted to a string. The process of conversion is also a serialization process.

Serialize to JSON string format with Json.dumps
Copy the Code code as follows:


>>> Import JSON
>>> dic {' Connection ': [' keep-alive '], ' Host ': [' 127.0.0.1:5000 '], ' cache-control ': [' max-age=0 ']}
>>> jdict = json.dumps ({' Connection ': [' keep-alive '], ' Host ': [' 127.0.0.1:5000 '], ' cache-control ': [' max-age= 0 ']})
>>> Print Jdict
{"Connection": ["keep-alive"], "Host": ["127.0.0.1:5000"], "Cache-control": ["Max-age=0"]}


Although DiC and jdict print the same strings, the actual types are different. DiC is a dictionary type and jdict is a string type
Copy CodeThe code is as follows:



>>> type (jdic)
>>> type (jdict)


You can use the Json.dumps serialization list as a JSON string format
Copy CodeThe code is as follows:


>>> list = [1, 4, 3, 2, 5]
>>> jlist = json.dumps (list)
>>> Print JList
[1, 4, 3, 2, 5]


The list and jlist types are also different
Copy CodeThe code is as follows:


>>> type (list)

>>> type (jlist)

Json.dumps has the following various parameters
Copy the Code code as follows:


Json.dumps (obj, Skipkeys=false, Ensure_ascii=true, Check_circular=true, Allow_nan=true, Cls=none, Indent=None, Separators=none, encoding= "Utf-8", Default=none, Sort_keys=false, **kw)


Key sort
Copy CodeThe code is as follows:


>>> Print Json.dumps ({1: ' A ', 4: ' B ', 3: ' C ', 2: ' d ', 5: ' F '},sort_keys=true)
{"1": "A", "2": "D", "3": "C", "4": "B", "5": "F"}

Format alignment
Copy the Code code as follows:


>>> Print json.dumps ({' 4 ': 5, ' 6 ': 7}, Sort_keys=true, indent=4)
{
"4": 5,
"6": 7
}


Specify delimiter
Copy CodeThe code is as follows:


>>> json.dumps ([1,2,3,{' 4 ': 5, ' 6 ': 7}], separators= (', ', ': '))
' [1,2,3,{' 4 ': 5, ' 6 ': 7}] '


Serializing to a file object with Json.dump
Copy CodeThe code is as follows:


>>> json.dump ({' 4 ': 5, ' 6 ': 7}, open (' Savejson.txt ', ' W '))
>>> Print open (' Savejson.txt '). ReadLines ()
[' {' 4 ': 5, ' 6 ': 7} ']

The Json.dump parameter is similar to Json.dumps
Copy the Code code as follows:


Json.dump (obj, FP, Skipkeys=false, Ensure_ascii=true, Check_circular=true, Allow_nan=true, Cls=none, Indent=None, Separators=none, encoding= "Utf-8", Default=none, Sort_keys=false, **kw)


Json.loads to deserialize a JSON string into a Python object

The function signature is:
Copy the Code code as follows:


Json.loads (s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]] [] ]]])


Note that the "s" here must be a string that is deserialized after the Unicode character
Copy CodeThe code is as follows:


>>> dobj = json.loads (' {' name ': ' AAA ', ' Age ': 18} ')
>>> type (dobj)
>>> print dobj
{u ' age ': ' U ' name ': U ' aaa '}


Json.load deserialize from file to Python The object

Signature is:
Copy code code as follows:


Json.load (fp[, encoding[, cls[, object_hook[, parse_float [, parse_int[, parse_constant[, object_pairs_hook[, **kw]] []]


Instance:
Copy code code as follows:


>>> fobj = json.load (' Savejson.tx T '))
>>> print fobj
{u ' 4 ': 5, U ' 6 ': 7}
>>> type (fobj)
  • 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.