Working with JSON data in Python

By: On:

In this tutorial, we will discuss Working with JSON data in Python. Also, We will see these below topics as:

  • JSON with python
  • Python extract data from JSON file
  • Extract specific data from JSON python
  • Read JSON file python
  • Python read JSON file line by line
  • Python object to JSON
  • Python create JSON array
  • Python write JSON to file pretty
  • Python string to JSON
  • Project using JSON

json with python

  • JSON stands for JavaScript Object Notation.
  • JSON is popular because of its lightweight data-interchange format.
  • JSON format looks like a dictionary in python
  • It is in a key and value format
  • JSON module always produce str objects.
  • dumps() : converting Python to JSON
  • loads() : converting JSON to Python

Python extract data from JSON file

In this section, we will learn how to extract data from JSON file in python.


Step 1: import json module

Step 2: Download dateset

Step 3: read file using open() and store it in f variable

Step 4: Parse f into python object using load().


Step 5: pass ‘Key‘index-number’key’& print the information.

ode: Our objective is to fetch the names of all teachers.

import json

f = open('data.json', 'r')
db = json.load(f)

print(db['teacher_db'][0]['name'])

Output:

In this output, we have printed name of all the teachers. db[‘teacher_db’][0][‘name’].
If this is confusing you then check the explanation in the next section (Extract field from JSON python).

JSON data in Python
JSON data in Python

Extract specific data from JSON python

Now, let us see how to extract specific data from JSON in Python.

  • Extracting information is an art.
  • In this section, we will learn how to get what we want.
  • While dealing with arrays, pay attention to nested arrays.
  • In the previous scenario, we used db['teacher_db'][0]['name'] to get the names of teachers.
  • where db is the variable that holds all the values that is why it is placed at the first position.
  • Now we have two options. (student_db & teacher_db)
  • We choose teacher_db, so we place it in the second position.
  • Now we have options (t_id, name, class, isPermanet)
  • each has an index value starting from 0 – 3.
  • Since we want a name so we provided the index value as [1] (the name is at position 1)
  • and then we mentioned key i.e [‘name’] in this case.
  • that is why the complete statement becomes db[‘teacher_db’][0][‘name’]
  • And this is how we extract the specific value.

Read JSON file python

In this section we will learn how to read json file in python.

Step 1: import the json module

Step 2: Use open() to read the json file and store this information in file variable.

Step 3: convert json to python using load() and store the information in db variable.

Step 4: Print the variable.

Code:

import json

with open('record.json') as file:
  db = json.load(file)

print(db)

Output:

The output displays all the information in the file, everything is in a key & value pair..

Read JSON file python
Read JSON file python

This is how we can read json file data in python.

Python read JSON file line by line

In this section, we will see how to read json file by line in Python and keep on storing it in an empty python list.

Step 1: import json module.

Step 2: Create empty python list with the name lineByLine

Step 3: Read the json file using open() and store the information in file variable.

Step 4: Convert item from json to python using load() & store the information in db variable.

Step 5: append db in lineByLine empty list.

Step 6: start a loop & print item of lineByLine list

Code:

import json

lineByLine = []
with open('record.json') as file:
    db = json.load(file)
    lineByLine.append(db)

for line in lineByLine:
    print(line[0],"\n",line[1],"\n",line[2])
    print(type(line[0]))

Output:

The output displays the content of json file line by line. Each item is displayed in different lines. The data type of each line is Python dict .

read json file by line in Python
read json file by line in Python

This is how we can read json file line by line in python.

Python object to JSON

Now, let us see how to convert Python object to json.

  • JSON is a javascript object. These objects need to be parsed to python objects and then only we can use & manipulate them.
  • json.dumps() is used to convert or parse python object to JSON

Code:

import json

people = {'name': 'vin',
 'age': 35,
  'profession': 'Software Engineer',
   'salary': 180000,
    'police_rec': False}
    
print(people)
print(type(people))
to_json = json.dumps(people)
print(to_json)
print(type(to_json))

Output:

In this output, python object i.e dict has been parsed or converted to json object i.e str.
Also, False & false have been pointed. python has False with uppercase ‘F‘ where has json has lowercase ‘f’.

parse python to json
Python object to JSON

Python create JSON array

  • Python Array plays a major role in data structuring.
  • In this section. we will learn how to create an array & nested array in Python.
  • nested array means array inside another array.
  • The number of nested-arrays determines the dimension of the object.

Code:

import json

with open('array.json') as file:
    db = json.load(file)


r = json.dumps(db, indent=2)
print(r)

Output:

In this output, multi-dimensional array is created using JSON.

create json array in python
Python create JSON array

Python write json to file pretty

  • Pretty does exactly how it sounds.
  • It improves the look of the output. Makes it more readable.
  • It displays data with indentation and sorting.
  • in JSON by default indent=none & Sort_file=false
  • But it can be changed to any value like indent = 2
  • And sort_file can be true. This will arrange all the keys in an ascending order.

Code:

import json

with open('array.json') as file:
    db = json.load(file)

print("Without PrettyPrint: \n", db)
print("\n")
r = json.dumps(db, indent=2)
print("with PrettyPrint: \n", r)

Output without prettyprint

In this output you can notice that everything is wrapped in 3 lines, it is not easy to understand.

Python write json to file pretty
Python write json to file pretty

Output with prettyprint

In this output you can see that it looks good & can be understand easily. All We did to make this data look like this is converted python to json using Dump and provided indentation of 2.

python working without json with pretty

Python string to JSON

  • In this section, we will learn how to convert string to JSON in Python
  • JSON always return ‘str’
  • So, no change will be visible here but it is converted to json.

Code:

import json

game = "God of war"
to_json = json.dumps(game)

print(type(to_json))

Output:

In this output, the string was converted to JSON and JSON always returns str that is why data type is still showing <class ‘str’>

convert string to JSON in Python
convert string to JSON in Python

Project using JSON

In this project, we are creating a dictionary using JSON. Users can search for the meaning of any word. In case the word is not available then the program will show an error prompt.

Scope for improvement:

Though the project is complete still there is scope for more features that you can try to add by yourself. In case, you face any problem, write in the comment box.

  • section to add new words
  • exit button
  • improve Gui.

Code:

import json
from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.geometry('300x140')
ws.title('Dictonary')

def find():
    k = word_Tf.get()
    try:
        with open('data.json') as f:
            db = json.load(f)
            meaning = db[k]
        return messagebox.showinfo('search result',meaning)
    except Exception as ep:
        return messagebox.showerror('error'," Word Not found!")
Label(ws, text='Enter word to search').place(x=30, y=10)
word_Tf = Entry(ws, width=40)
word_Tf.place(x=30, y=30)

search_Btn = Button(ws, text="Search", command=find, padx=20, pady=5, width=10)
search_Btn.place(x=145, y=70, anchor=CENTER)

ws.mainloop()

Output:

In this output, a dictionary application is created. You can search for any meaning of a word. The meaning of the word will be shown using a popup message box. In case the word is not available error pop-up message will appear.

Working with JSON data in Python dictionary using json

In case, you the word is not available in the JSON file then you will will see error message.

Working with JSON data in Python error

You may like the following Python tutorials:

We have learned these:

  • JSON with python
  • Python extract data from JSON file
  • Extract specific data from JSON python
  • Read JSON file python
  • Python read JSON file line by line
  • Python object to JSON
  • Python create JSON array
  • Python write JSON to file pretty
  • Python string to JSON
  • Project using JSON

Leave a Comment