Python json module usage examples

高洛峰
Release: 2017-01-13 13:14:18
Original
1150 people have browsed it

In fact, JSON is the string representation of a Python dictionary, but as a complex object, the dictionary cannot be transferred directly, so it needs to be converted into a string form. The conversion process is also a serialization process.

Use json.dumps to serialize into json string format

>>> 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"]}
Copy after login

Although the strings printed by dic and jdict are the same, their actual types are different. dic is a dictionary type and jdict is a string Type

<type &#39;dict&#39;>
>>> type(jdic)
>>> type(jdict)
<type &#39;str&#39;>
Copy after login

You can use json.dumps to serialize the list into json string format

>>> list = [1, 4, 3, 2, 5] 
>>> jlist = json.dumps(list)
>>> print jlist
[1, 4, 3, 2, 5]
Copy after login

list and jlist types are also different

>>> type(list)
<type &#39;list&#39;>
>>> type(jlist)
<type &#39;str&#39;>
Copy after login

json.dumps has the following Parameters

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

key sorting

>>> print json.dumps({1:&#39;a&#39;, 4:&#39;b&#39;, 3:&#39;c&#39;, 2:&#39;d&#39;, 5:&#39;f&#39;},sort_keys=True)
{"1": "a", "2": "d", "3": "c", "4": "b", "5": "f"}
Copy after login

Format alignment

>>> print json.dumps({&#39;4&#39;: 5, &#39;6&#39;: 7}, sort_keys=True, indent=4)
{
    "4": 5, 
    "6": 7
}
Copy after login

Specify delimiter

>>> json.dumps([1,2,3,{&#39;4&#39;: 5, &#39;6&#39;: 7}], separators=(&#39;,&#39;,&#39;:&#39;))
&#39;[1,2,3,{"4":5,"6":7}]&#39;
Copy after login

Use json.dump to serialize into a file object

>>> json.dump({&#39;4&#39;: 5, &#39;6&#39;: 7}, open(&#39;savejson.txt&#39;, &#39;w&#39;))
>>> print open(&#39;savejson.txt&#39;).readlines()
[&#39;{"4": 5, "6": 7}&#39;]
Copy after login

json.dump parameters are similar to json.dumps

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

json.loads deserializes json strings into python objects

The function signature is:

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Copy after login

Note that the "s" here must be a string, which will be a unicode character after deserialization

>>> dobj = json.loads(&#39;{"name":"aaa", "age":18}&#39;)
>>> type(dobj)
<type &#39;dict&#39;>
>>> print dobj
{u&#39;age&#39;: 18, u&#39;name&#39;: u&#39;aaa&#39;}
Copy after login

json.load is deserialized from the file into a python object

The signature is:

json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Copy after login

Examples:

>>> fobj = json.load(open(&#39;savejson.txt&#39;))
>>> print fobj
{u&#39;4&#39;: 5, u&#39;6&#39;: 7}
>>> type(fobj)
<type &#39;dict&#39;>
Copy after login

For more articles related to Python json module usage examples, please pay attention to the PHP Chinese website!

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