Home > Article > Backend Development > Detailed explanation of Python parsing JSON
Using the JSON function requires importing the json library: import json.
Function Description
json.dumps Encode Python object into JSON String
json .loads Decodes the encoded JSON string into a Python object
Syntax
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)
Example
The following example encodes the array into JSON format data:
#!/usr/bin/python import json data = {'number': 6, 'name': 'Pythontab'} jsonData = json.dumps(data) print jsonData
The execution result of the above code is:
{"number": 6, "name": "Pythontab"}
Note: You may find that when performing the above conversion From now on, the data has not changed. Here is what I want to say: In json, double quotes are the string separator, and single quotes are not standard.
Use parameters to sort JSON data and format the output:
#!/usr/bin/python import json data = {'number': 6, 'name': 'Pythontab'} jsonData = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')) print jsonData
Output results
{ "name": "Pythontab", "number": 6 }
Conversion table from python original type to json type:
Python | JSON |
---|---|
object | |
list, tuple | array |
string | |
float | number|
true | |
false | |
null |
data type of the Python field.
Syntaxjson.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]] ]])ExamplesThe following examples show how Python decodes JSON objects:#!/usr/bin/python import json jsonData = '{"number": 6, "name": "Pythontab"}' str = json.loads(jsonData) print strThe execution result of the above code is:
{u'number': 6, u'name': u'Pythontab'}json
Type conversion table to python:
Python | |
---|---|
dict | |
list | |
unicode | |
int, long | |
float | |
True | |
False | |
None |
Environment configuration
Method 1: Source code installation
$ tar -xvzf demjson-2.2.4.tar.gz$ cd demjson-2.2.4$ python setup.py installMethod 2: Use pip to install directlypip install DemjsonJSON functionFunction Descriptionencode Encode Python objects into JSON stringsdecode You can use the demjson.decode() function to decode JSON data. This function returns the data type of the Python field. encode syntaxdemjson.encode(self, obj, nest_level=0)decode syntaxdemjson.decode(self, txt)The above is the detailed content of Detailed explanation of Python parsing JSON. For more information, please follow other related articles on the PHP Chinese website!