When using JSON in Python, which is primarily the use of JSON modules, JSON interacts with data in a good format so that, 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 json.load (open (' Kel.txt '))
# Deserialize string or Unicode to Python object
j = json.loads (open (' kel.txt '). Read (), encoding= ' Utf-8 ')
print Type (j), J for
I in J:
print i
k = json.dumps (j,encoding= ' Utf-8 '). Decode (' Utf-8 ')
print K
The contents of the Kel.txt file are as follows:
{"
Chinese": "Kel", "
Fist": "Kel"
The results of the implementation 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
In which the main methods used are json.loads and json.dumps
Note the argument must be string in loads to use the Read method when opening the file, otherwise there will be an error.
The loads method is primarily used to load JSON data into objects in Python, and the Dumps method is primarily to modify the Python object to JSON format.
An error began to be encountered as follows:
[Root@python 56]# python kel.py
traceback (most recent call last):
File ' kel.py ', line 5, in <module>
JS On.load (Open (' Kel.txt '))
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/decoder.py", line 364, in decode
obj, end = Self.raw_decode (S, idx=_w (s, 0). End ())
File "/usr/local/python/lib/python2.7/json/decoder.py", line 382, in Raw_ Decode
Raise ValueError ("No JSON object could be decoded")
The main reason is that, in JSON, the data format must begin with double quotes, and the error JSON file is as follows:
kel.py contents are as follows:
#!/usr/bin/env python
#-*-coding:utf-8-*-
import json
j = json.loads (open (' kel.txt '). Read ())
print Type (j), J
Double quotes ... Single quotation marks, silly points are not clear
Sometimes, in the loads method, it is because the string of single quotes is generated ... This is especially true in Python, which has nothing to do with anything else, mainly the relationship between quotes!!!
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.