Python Create JSON File

Problem Formulation and Solution Overview

This article focuses on working with a JSON file. JSON is an acronym for JavaScript Object Notation. This is a flat-text file formatted based on JavaScript (JS) Syntax.

This file is most commonly noted for its ability to transmit data to/from web applications, such as sending/receiving data from a Server/Client to display or retrieve said data.

The JSON file structure has keys and values similar to a Python Dictionary.

This structure can contain strings, boolean, integers, floats, lists, and much more. This file structure can be as simple or complex as needed.

This article works with Rivers Clothing, a new start-up. They have hired their first three (3) employees. This employee data is displayed as a List of Dictionaries.

emps = {"hires": [{"ID": 324,
                   "name": "Alex Smith",
                   "title": "Manager"},
                  {"ID": 325,
                   "name": "Micah Jones",
                   "title": "Designer"},
                  {"ID": 326,
                   "name": "Sam Quinn",
                   "title": "Coder"}]}

πŸ’¬ Question: How would we write code to create and work with a JSON File?

  1. Python Create JSON File if Not Exists
  2. Python Create JSON String from List of Dictionaries
  3. Python Create JSON File and Write Data
  4. Python Read JSON File
  5. Python Access JSON Elements
  6. Python Delete JSON Elements

Python Create JSON File if Not Exists

This example creates an empty JSON file if one does not exist in the current working directory.

import os

filename = 'employees.json'
isFile = os.path.isfile(filename)

if (not isFile):
    with open(filename, 'w') as fp:
        pass
else:
    print(f'The {filename} file exists.')

The first line in the above code snippet imports Python’s built-in os library. This allows access to and manipulation of files and folders.

The following line declares the JSON file name, employees.json and saves it to the variable filename.

The next line calls the os.path.isfile() function and passes it one (1) argument, filename. This function checks the current directory for the existence of the employees.json file

The first time this code runs, and this file is not found (isFile is False), an empty file is created and placed into the current working directory.

πŸ’‘Note: The pass statement is a placeholder code and does nothing when executed. This is used here so a file is created, and nothing else occurs.

If this code is rerun or the file exists, the following message is output to the terminal.

The employees.json file exists.

To create this file in a sub-folder, you would modify the code as follows:

import os

filename = 'files\\employees.json'
isFile = os.path.isfile(filename)

if (not isFile):
    with open(filename, 'w') as fp:
        pass
else:
   print(f'The {filename} file exists.')

When this code runs, the files folder is checked for the existence of the employees.json file.


Python Create JSON String from List of Dictionaries

This example creates a JSON string from a List of Dictionaries.

import json

emps = {"hires" :[{"empID": "RC-3243",
                   "name": "Alexa Smith",
                   "title": "Manager"}, 
                  {"empID": "RC-3244",
                   "name": "Micah Jones",
                   "title": "Designer"}, 
                  {"empID": "RC-3245",
                   "name": "Sam Quinn",
                   "title": "Coder"}]}

json_str = json.dumps(emps, indent=4)
print(json_str)

The above code snippet imports the json library. This library allows access to JSON functions.

The following three (3) lines construct a List of Dictionaries containing data for the new hires. The results save to emps.

Next, json.dumps() is called and passed two (2) arguments: a List of Dictionaries, emps, and for formatting, spaces to indent. The results save to json_str and output to the terminal.

{
"hires": [
      {
                "ID": 3243,
                "name": "Alexa Smith",
                "title": "Manager"
       },
      {
               "ID": 3244,
               "name": "Micah Jones",
               "title": "Designer"
       },
      {
            "ID": 3245,
            "name": "Sam Quinn",
           "title": "Coder"
      } 
  ]
}

πŸ’‘Note: The json.dumps() function formats the JSON string. To write this to a file, json.dump() is used.


Python Create JSON File and Write Data

This example writes a List of Dictionaries to a JSON file.

import os
import json

filename = 'employees.json'
isFile = os.path.isfile(filename)
 
emps = {"hires" :[{"ID": 3243, "name": "Alexa Smith", "title": "Manager"}, 
                  {"ID": 3244, "name": "Micah Jones", "title": "Designer"}, 
                  {"ID": 3245, "name": "Sam Quinn", "title": "Coder"}]}

if (not isFile):
    with open(filename, 'w') as fp:
        json.dump(emps, fp, indent=4)
else:
    print(f'An error occurred writing to {filename}.')           
 

The above code snippet adds the two (2) highlighted lines to write the formatted JSON string to the employees.json file.

The contents of this file is as follows:

{
"hires": [
      {
                "ID": 3243,
                "name": "Alexa Smith",
                "title": "Manager"
       },
      {
               "ID": 3244,
               "name": "Micah Jones",
               "title": "Designer"
       },
      {
            "ID": 3245,
            "name": "Sam Quinn",
           "title": "Coder"
      } 
  ]
}

Python Read JSON File

In this example, the JSON file saved earlier is read back in.

import os
import json

filename = 'employees.json'
json_str = ''

with open(filename , 'r') as fp:
    for l in fp:
        l.replace('\n', '')
        json_str += l

print(json_str)

This code snippet opens, reads the employees.json file and saves it to json_str. Upon each iteration, any additional newline (\n) characters are removed using the replace() function.

Once all lines have been read, the contents of json_str is output to the terminal and is the same as indicated above.


Python Access JSON Elements

This example reads in the previously saved JSON file and accesses the ID element from each hire.

import os
import json

filename = 'employees.json'
json_str = ''

with open(filename , 'r') as fp:
    for l in fp:
        l.replace('\n', '')
        json_str += l

all_emps = json.loads(json_str)
alexa_id = all_emps['hires'][0]['ID']
sam_id = all_emps['hires'][2]['ID']
print(alexa_id, sam_id)

As outlined earlier in this article, the employees.json file is read in, parsed and saved to json_str.

Then, json_str is loaded using json_loads() and passed one (1) argument, the json_str created above. This gives us access to the elements.

The following lines access the Employee IDs for Alexa and Micah and outputs same to the terminal.

3243 3245

To iterate and display the ID and name for each new hire, run the following code:

import os
import json

filename = 'employees.json'
json_str = ''

with open(filename , 'r') as fp:
    for l in fp:
        l.replace('\n', '')
        json_str += l

all_emps = json.loads(json_str)

for item in all_emps['hires']:
    print(item['ID'], item['name'])

Another option is to use List Comprehension to retrieve the data:

results = [item['ID'] for item in all_emps['hires']]
print(results)

Python Delete Elements

This example reads in the previously saved JSON file and deletes the new hire, Micah Jones.

import os
import json

filename = 'employees.json'
json_str = ''

with open(filename , 'r') as fp:
    for l in fp:
        l.replace('\n', '')
        json_str += l

all_emps = json.loads(json_str)
idx = 0

for item in all_emps['hires']:
    if idx == 1:
        del all_emps['hires'][idx]
    idx += 1
print(all_emps)

Summary

We hope you enjoyed this article about converting a List of Dictionaries to JSON and everything in between!

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd