Example of how to parse a json file in python,
Preface
JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript (Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language. Easy for reading and writing, and easy for machine parsing and generation.
This article describes how to parse json files in python. parsing json files is nothing more than encoding and decoding. Here we use the built-in json module in python. Of course, we also need to combine the unique dict operations of python. Let's take a look at the detailed introduction.
Encoding
Encoding is usedjson.dumps()
Function to convert the dictionary into a json object.
Import jsondata = [{'A': "a", 'B' :( 2, 4), 'C': 3.0}] # list object print "DATA:", repr (data) data_string = json. dumps (data) # dumps function print "JSON:", data_string
The output result is:
DATA: [{'A': 'A', 'C': 3.0, 'B' :( 2, 4)}] # python dict DATA is JSON Without sequential storage: [{"a": "A", "c": 3.0, "B": [2, 4]}]
Decoding
Decodingjson.loads()
Function to convert the json format to dict.
Import jsondata = '{"a": "A", "B": [2, 4], "c": 3.0}' # json format decoded = json. loads (data) print "DECODED:", decoded
The output result is
DECODED: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}]
In the process of encoding and decoding, tuples are converted into unordered lists, and the dictionary order cannot be changed.
Now, the focus of processing the json format is to correctly process the dict data.
Common Errors
The json module of python does not support single quotes, so it is similar"{'a':'A','b':[2,4],'c':3.0}"
The following error is reported:
ValueError: Expecting property name: line 1 column 2 (char 1)
At this time, we only need to swap his single double quotes:
'{"a":"A","b":[2,4],"c":3.0}'
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.