How to Write JSON File in Python

JSON is the most popular format for records serialization; given how generally applicable and lightweight its miles are also reasonably human-pleasant. JSON is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this json, we import the json package in Python script.

The text in JSON is done through quoted-string, which contains the value in key-value mapping within { }. It is similar to the dictionary in Python, and it is drastically used inside the web development international. You may probably come across JSON-serialized items sent from rest APIs, utility configuration, or even easy information storage.

Python has a built-in package called json, which is used to work with JSON data.

How to Write JSON File in Python

To write a json file in Python, serialize an object to json using json.dump() method and use the with open() function. The json.dump() is a built-in Python function that converts the Python objects into appropriate json objects. The json.dump() method is used when the objects have to be stored in a file.

Serializing JSON refers to transforming records into a chain of bytes to be saved or transmitted across a network. To address the records that go with the flow in a report, the JSON library in Python uses the dump() or dumps() function to transform the Python objects into their respective JSON element, making it clean to write down facts documents.

Syntax

json.dump(dictionary, indent)

Arguments

  1. Dictionary name – The dictionary’s name should be converted to a JSON object.
  2. Indent – It defines the number of units for indentation.

Convert a dictionary to json using json.dump()

To convert a dictionary to json, use the json.dump() method.

import json

data = {'students':
  [{
    'name': 'anand godhani',
    'GR no': 54468,
    'department': 'computer engineering',
   },
   {
    'name': 'Nishant patel',
    'GR no': 64842,
    'department': 'chemical Engineering',
  },
  {
    'name': 'Dhruv busa',
    'GR no': 49724,
    'department': 'Bsc',
  }]
}

json_string = json.dumps(data)
print(json_string)

Output

{"students": [{"name": "anand godhani", "GR no": 54468, "department": "computer engineering"}, 
{"name": "Nishant patel", "GR no": 64842, "department": "chemical Engineering"}, 
{"name": "Dhruv busa", "GR no": 49724, "department": "Bsc"}]}

We converted a dictionary to json using the dump() method. To write a json content into a file in Python, use the open() function.

with open("data.json", "w") as i :
   json.dump(json_string, i)

Output

It will create the data.json file in the current directory with the following contents.

"{\"students\": [{\"name\": \"anand godhani\", \"GR no\": 54468, \"department\": \"computer engineering\"}, 
{\"name\": \"Nishant patel\", \"GR no\": 64842, \"department\": \"chemical Engineering\"}, 
{\"name\": \"Dhruv busa\", \"GR no\": 49724, \"department\": \"Bsc\"}]}"

Converting Python objects of the following types into JSON strings

  1. dict
  2. list
  3. tuple
  4. string
  5. int
  6. float
  7. True
  8. False
  9. None
import json

print(json.dumps("hello "))
print(json.dumps(50))
print(json.dumps(54.24))
print(json.dumps(False))

Output

"hello "
50
54.24
false

When you convert from Python object to JSON

Python

                                           JSON Equivalent

dict

object

list, tuple

array

str

string

int, long, float

numbers

True

true

False

false

None

null

 

Code for converting a Python object containing all the data types

import json

data = {
   "name": "Jay",
   "age": 20,
   "married": True,
   "divorced": False,
   "children": ("Deep", "Riya"),
   "pets": "dog",
   "Vehicle": [
   {
    "Bike": "Hero splender", "Car": "Mini cooper"
   },
   ]
   }

print(json.dumps(data))

Output

{"name": "Jay", "age": 20, "married": true, "divorced": false, 
 "children": ["Deep", "Riya"], "pets": "dog", 
  "Vehicle": [{"Bike": "Hero splender", "Car": "Mini cooper"}]}

It is not easy to read, with no indentations and line breaks. The json.dumps() method has parameters to make it easier to read the result: Use four indents to make it easier to read the result:

print(json.dumps(data, indent=4))

Output

{
    "name": "Jay",
    "age": 20,
    "married": true,
    "divorced": false,
    "children": [
        "Deep",
        "Riya"
    ],
   "pets": "dog",
   "Vehicle": [
      {
          "Bike": "Hero splender",
          "Car": "Mini cooper"
      }
   ]
}

Separator: Use the separators parameter to change the default separator.

Use ~ and a space to separate objects and a space to separate keys from their values:

print(json.dumps(data, indent=4, separators=("~ ", " = ")))

Output

{
    "name" = "Jay"~
    "age" = 20~
    "married" = true~
    "divorced" = false~
    "children" = [
    "Deep"~
    "Riya"
    ]~
  "pets" = "dog"~
  "Vehicle" = [
     {
         "Bike" = "Hero splender"~
         "Car" = "Mini cooper"
     }
   ]
}

sort_keys: Use the sort_keys parameter to specify if the result should be sorted or not. If the sort_keys are True, it will be sorted by the index.

print(json.dumps(data, indent=4, sort_keys=True))

Output

{
    "Vehicle": [
       {
           "Bike": "Hero splender",
           "Car": "Mini cooper"
       }
    ],
    "age": 20,
    "children": [
           "Deep",
           "Riya"
     ],
     "divorced": false,
     "married": true,
     "name": "Jay",
     "pets": "dog"
}

That’s it for this tutorial.

See also

Python list files in a directory

Read the first line in Python

Leave a Comment