JSON Python : Read, Write, and Parse JSON Files in Python

JSON, short for JavaScript Object Notation, is a data format used for transmitting and receiving data between servers and web applications. It stores data as a quoted string in a key: value pair within curly brackets. Python provides support for JSON objects through a built-in package called “json.” With the JSON Python package, you can convert JSON files to Python objects and vice versa, to share data on Python web apps.

The JSON Python package usually stores data as a string, but it can also store it in a file. To work with JSON files and convert Python objects to JSON, you need to import the Python json module.

How to Write JSON to a File?

After importing the JSON Python module, you can write JSON onto a file. The package provides a method called json.dump() that allows writing JSON to a file. The json.dump() function allows writing JSON to file with no conversion. The json.dump() method accepts two arguments:

  • Dictionary: Name of the dictionary
  • File pointer: File pointer in open or append mode

Example: Writing JSON to a File Using json.dump() in JSON Python Package

In the code below, you will create a file named example.json and convert a dictionary into a JSON object using the json.dumps() method. This is how it goes.

import json

# Initializing dictionary

dic_exm ={

"name" : "Simplilearn",

"roll_no" : 1,

"cgpa" : 9.68,

"phone_num" : "1231252123"

}

with open("example.json", "w") as outfile:

json.dump(dic_exm, outfile)

Output:

JSONPython_1.

How to Convert From JSON to Python?

The JSON Python module also allows you to convert a JSON String to Python by using the json.loads() method. The result of this conversion will be a dictionary.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

Example: Converting JSON String to a Python Dictionary

import json

# Random JSON String

i =  '{ "name":"Rahul", "age":23, "city":"Mumbai"}'

# Converting JSON to Python

j = json.loads(i)

# Extracting values from the resultant Dictionary

print(j["name"])

print(j["age"])

print(j["city"])

print(j)

Output:

JSON_Python_2

Various Types of Python Objects That Can Be Converted to JSON Strings

With the JSON Python, you can convert the following Python objects to JSON strings:

The code below uses all the Python objects mentioned above and converts them to JSON using the .dumps() method from the JSON Python package.

import json

print(json.dumps({"name": "Simplilearn", "age": 5}))

print(json.dumps(["Mercedes Benz", "BMW"]))

print(json.dumps(("Fruits", "Juice")))

print(json.dumps("HI!"))

print(json.dumps(120))

print(json.dumps(19.15))

print(json.dumps(True))

print(json.dumps(False))

print(json.dumps(None))

Output:

JSON_Python_3.

As you can see from the above code, after the conversion, the Python objects turn into their JSON equivalent, which are:

Python

JSON

dict

Object

list

Array

tuple

Array

str

String

int

Number

float

Number

True

true

False

false

None

null

How to Convert From Python to JSON?

Similar to json.dump() method, the json Python also provides json.dumps() method. The only difference between the two is that json.dumps() converts a dictionary to a JSON object and json.dump() writes a JSON to file without the conversion. The json.dumps() method accepts the following two arguments:

  • Dictionary: Name of the dictionary
  • Indent: Number of units for indentations

Besides these two, the json.dumps() method also accepts several other parameters for formatting and sorting the results. You will look at those parameters later in this article.

Example: Converting Python to JSON Using json.dumps() from JSON Python Package

For this example, you will use the same example that was used while learning the json.dump() method but this time with the json.dumps() method.

import json

# Initializing dictionary

dic_exm ={

"name" : "Simplilearn",

"roll_no" : 1,

"cgpa" : 9.68,

"phone_num" : "1231252123"

}

# Serializing json

json_obj = json.dumps(dic_exm, indent = 4)

# Writing to sample.json

with open("example.json", "w") as outfile:

outfile.write(json_obj)

Output:

JSON_Python_4

How to Format the JSON Python Result?

Before beginning, let’s look at the code below.

import json

i = {

  "name": "Rahul",

  "age": 15,

  "married": True,

  "divorced": False,

  "children": ("Hari","Sam"),

  "brothers": None,

  "cars": [

    {"model": "Mercedes-Benz", "mpg": 27.5},

    {"model": "Ferrari", "mpg": 24.1}

  ]

}

print(json.dumps(i))

Output:

JSON_Python_5

As you can see in the code above, you get a JSON string, but it is not readable. Thus the JSON Python package allows formatting the results to make them easier to read with indentations and separators.

FREE Data Science With Python Course

Start Learning Data Science with Python for FREEStart Learning
FREE Data Science With Python Course

Example: Formatting the JSON Python Results With Indentations

The indent argument in the json.dumps() method will indent the result from the left by the mentioned numbers. You will use the same example as above, but use the indentation this time to see the difference.

import json

i = {

  "name": "Rahul",

  "age": 15,

  "married": True,

  "divorced": False,

  "children": ("Hari","Sam"),

  "brothers": None,

  "cars": [

    {"model": "Mercedes-Benz", "mpg": 27.5},

    {"model": "Ferrari", "mpg": 24.1}

  ]

}

print(json.dumps(i, indent=8))

Output:

JSONPython_6

As you can see in the above code, the result is indented and much more readable.

Example: Formatting the JSON Python Results With Separators

Similar to indent, the json.dumps() method also takes a separator’s argument. You can use it to include different types of separators to format the result. For instance, the default separators value (“, ”, ”: ”) means using a comma and space to separate each dictionary object and using a colon and space to separate keys from their values. Here’s an example for using the separator argument.

import json

i = {

  "name": "Rahul",

  "age": 15,

  "brothers": None,

  "cars": [

    {"model": "Mercedes-Benz", "mpg": 27.5},

    {"model": "Ferrari", "mpg": 24.1}

  ]

}

print(json.dumps(i, indent=8, separators=(". ", "= ")))

Output:

JSONPython_7

As you can see in the above output, the objects are separated by a “.” sign, and the key: value pairs are separated by an “=” character.

How to Order the JSON Python Results?

You can also pass the sort_keys parameter to order the JSON Python results. To sort the results, you can pass true in the parameter. When you pass true, it will sort the results in ascending order. The example below uses the sort_keys parameter to sort the output.

Example: Using the sort_keys Parameter to Sort JSON Python Result

import json

i = {

  "name": "Rahul",

  "age": 15,

  "brothers": None,

  "cars": [

    {"model": "Mercedes-Benz", "mpg": 27.5},

    {"model": "Ferrari", "mpg": 24.1}

  ]

}

print(json.dumps(i, indent=8, sort_keys=True))

Output:

JSONPython_8

As you can see in the above code, it shows the results in alphabetical order.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Summing It Up

In this article, you have learned everything about the JSON Python package. You have also seen how to convert JSON to Python and vice versa with various examples. Having in-depth knowledge about JSON Python will help you seamlessly store and transmit data between the servers and your Python web application. 

Python is a widely popular programming language. If you want to become a Python or a full-stack developer, you must be clear with your basics. You can refer to Simplilearn’s Python Tutorial for Beginners for getting your base strong. Once you are done with that, you can opt for the Online Python Certification Course. The course will help you understand basic and advanced Python concepts with hands-on experience on several frameworks to help you excel in this field.

Have any questions for us? Mention them in the comments section of this article. Our experts will get back to you on the same, soon!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.