When using json in Python, the main thing is to use the json module. Json interacts with data in a good format, so in many cases, the json data format can be used as an interface between programs.
#!/usr/bin/env python #-*- coding:utf-8 -*- import json print (open('')) #deserialize string or unicode to python object j = (open('').read(),encoding='utf-8') print type(j),j for i in j: print i k = (j,encoding='utf-8').decode('utf-8') print k
The file contents are as follows:
{ "Chinese":"kel", "fist":"kel" }
The execution results are as follows:
{u'\u4e2d\u6587': u'kel', u'fist': u'kel'} <type 'dict'> {u'\u4e2d\u6587': u'kel', u'fist': u'kel'} Chinese fist {"\u4e2d\u6587": "kel", "fist": "kel"}
The main methods used are
Note that the parameter in loads must be string, so when opening the file, you must use the read method, otherwise an error will occur.
The loads method is mainly used to load json data and become objects in python, while the dumps method mainly changes python objects to json format.
I first encountered an error as follows:
[root@python 56]# python Traceback (most recent call last): File "", line 5, in <module> (open('')) File "/usr/local/python/lib/python2.7/json/__init__.py", line 291, in load **kw) File "/usr/local/python/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/local/python/lib/python2.7/json/", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/python/lib/python2.7/json/", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded
The main reason is that,,,, in the data format of json, must start with double quotes, and the wrong json file is as follows:
{ "fist":'kel' }
The content is as follows:
#!/usr/bin/env python #-*- coding:utf-8 -*- import json j = (open('').read()) print type(j),j
Double quotes. . . Single quotes, stupidly not clear
Sometimes, when performing the loads method, it is because a single quote string is generated. . . This is especially true in python, it has nothing to do with other things, it is mainly the relationship between quotes! ! !
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.