Example of a method in python to parse an json file

  • 2020-06-01 10:03:58
  • OfStack

preface

JSON(JavaScript Object Notation) is a lightweight data interchange 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 also USES habits similar to those of the C language family (C, C++, C#, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language. Easy for people to read and write, but also easy for machines to parse and generate.

This paper mainly introduces the method of parsing json files in python, while parsing json files is nothing more than encoding and decoding. Here we use the json module which comes with python. Also, of course, combine python's own dict type of operations. Let's take a look at the details.

coding

This is what the code USES json.dumps() Function to convert a dictionary into an json object.


import json
data = [{'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 the dict Types of data are not stored in order 
JSON: [{"a":"A","c":3.0,"b":[2,4]}]

decoding

Decoding with json.loads() Function to convert json format to dict.


import json
data = '{"a":"A","b":[2,4],"c":3.0}' #json format 
decoded = json.loads(data)
print "DECODED:",decoded

The output is


DECODED: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}]

During encoding and decoding, tuples are turned into unordered lists, and the order of dictionaries is not guaranteed to remain the same.

Now, the point of processing the json format is to properly process the dict type data.

Common mistakes

python's json module does not support single quotes, so it is similar "{'a':'A','b':[2,4],'c':3.0}" The following error is reported for the string:


ValueError: Expecting property name: line 1 column 2 (char 1)

In this case, we just need to swap the quotation marks:


'{"a":"A","b":[2,4],"c":3.0}'

conclusion


Related articles: