Home >Backend Development >Python Tutorial >Python json module usage examples
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"]}
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 'dict'> >>> type(jdic) >>> type(jdict) <type 'str'>
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]
list and jlist types are also different
>>> type(list) <type 'list'> >>> type(jlist) <type 'str'>
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)
key sorting
>>> 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
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) { "4": 5, "6": 7 }
Specify delimiter
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]'
Use json.dump to serialize into a file object
>>> json.dump({'4': 5, '6': 7}, open('savejson.txt', 'w')) >>> print open('savejson.txt').readlines() ['{"4": 5, "6": 7}']
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)
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]]]]]]]])
Note that the "s" here must be a string, which will be a unicode character after deserialization
>>> dobj = json.loads('{"name":"aaa", "age":18}') >>> type(dobj) <type 'dict'> >>> print dobj {u'age': 18, u'name': u'aaa'}
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]]]]]]]])
Examples:
>>> fobj = json.load(open('savejson.txt')) >>> print fobj {u'4': 5, u'6': 7} >>> type(fobj) <type 'dict'>
For more articles related to Python json module usage examples, please pay attention to the PHP Chinese website!