Linux

Python With JSON

In this chapter we will study about JSON file and intraction of Python with JSON file.

JSON

JSON stands for JavaScript Object Notation. Consider a simple file which contain the records.
 JSON file
Simple File
Click to view file
Now we change this code to JSON file.
 JSON file
JSON file
Click to view file
You have seen the combination of dictionary, list and internal dictionaries. I have used here ID field, aim to denote line number.

Python with JSON

In this section we will see, Python read and write operation on JSON file.

Python read JSON file

In order to read JSON file first you have to import JSON module. Let us see the code then discuss about it.
 json.loads(data) Python JSON
Python JSON read
Click to view file
data = f.read() is the data read from file. You can see json.load(data) is used to load the JSON data. The jsondata is the dictionary of currently contain one key Records.
The jsondata["Records"] is the list, which contains the jsondata dictionary's item has key Records .
The jsondata["Records"][0] is first element of list jsondata["Records"]

Python Write JSON file

In order to read JSON file first you have to import JSON module. Let us see the code then discuss about it.
 json.loads(data) Python JSON write
Python JSON write
Click to view file
In order to write JSON file we will use json.dump(jsondata,fw, indent=2). The function json.dump() dump the jsondata dictionary in to file newdata5.json. The keyword indent is used to give indentation in file.

JSON file operation by Python

You have learned how to read and write JSON file. Now you will learn simple JSON file operation using Python.
Consider the file newdata5.json and you want to extract the record containing word "mill".
Let us discuss with code.
 json.loads(data) Python JSON
Python JSON operation
Click to view code
One list jsondata1 and one dictionary dict have created. From line 7 you can see the list list1 contains the all records. From line 9 for loop, val contains internal dictionaries. Line 9, line contains the actual record. Line flag= line.find("mill") would find that word "mill" exists in line or not, if exists it will return positive number. The list jsondata1 will be populating. Then this list fixed as item of dictionary dict then dictionary dumped into new file as shown below.
 json.loads(data) Python JSON
Python JSON new file
Click to view file
You can see the file is showing the records containing "mill" word.





admin