11-03-2022, 01:09 PM
Python Create JSON File
5/5 – (1 vote)
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.
Question: How would we write code to create and work with a JSON File?
Python Create JSON File if Not Exists
This example creates an empty JSON file if one does not exist in the current working directory.
The first line in the above code snippet imports Python’s built-in library. This allows access to and manipulation of files and folders.
The following line declares the JSON file name, and saves it to the variable .
The next line calls the function and passes it one (1) argument, . This function checks the current directory for the existence of the file
The first time this code runs, and this file is not found (is False), an empty file is created and placed into the current working directory.
Note: The 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 file exists.
To create this file in a sub-folder, you would modify the code as follows:
When this code runs, the files folder is checked for the existence of the file.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPcrUJjfmOwE%2Fhqdefault.jpg)
Python Create JSON String from List of Dictionaries
This example creates a JSON string from a List of Dictionaries.
The above code snippet imports the 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.
Next,is called and passed two (2) arguments: a List of Dictionaries, , and for formatting, spaces to indent. The results save to and output to the terminal.
Note: The function formats the JSON string. To write this to a file, is used.
Python Create JSON File and Write Data
This example writes a List of Dictionaries to a JSON file.
The above code snippet adds the two (2) highlighted lines to write the formatted JSON string to the file.
The contents of this file is as follows:
Python Read JSON File
In this example, the JSON file saved earlier is read back in.
This code snippet opens, reads the file and saves it to . Upon each iteration, any additional newline () characters are removed using the function.
Once all lines have been read, the contents of is output to the terminal and is the same as indicated above.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-UkcLQxzPA4%2Fhqdefault.jpg)
Python Access JSON Elements
This example reads in the previously saved JSON file and accesses the ID element from each hire.
As outlined earlier in this article, the file is read in, parsed and saved to .
Then,is loaded using and passed one (1) argument, the 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.
To iterate and display the and for each new , run the following code:
Another option is to use List Comprehension to retrieve the data:
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qsq2Vf48W8%2Fhqdefault.jpg)
Python Delete Elements
This example reads in the previously saved JSON file and deletes the new hire, Micah Jones.
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
[i]“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[/i]
5/5 – (1 vote)
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.
Code:
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?- Python Create JSON File if Not Exists
- Python Create JSON String from List of Dictionaries
- Python Create JSON File and Write Data
- Python Read JSON File
- Python Access JSON Elements
- 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.
Code:
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
Code:
osThe following line declares the JSON file name,
Code:
employees.jsonCode:
filenameThe next line calls the
Code:
os.path.isfile()Code:
filenameCode:
employees.jsonThe first time this code runs, and this file is not found (
Code:
isFile
Note: The Code:
passIf this code is rerun or the file exists, the following message is output to the terminal.
The
Code:
employees.jsonTo create this file in a sub-folder, you would modify the code as follows:
Code:
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
Code:
employees.jsonPython Create JSON String from List of Dictionaries
This example creates a JSON string from a List of Dictionaries.
Code:
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
Code:
jsonThe following three (3) lines construct a List of Dictionaries containing data for the new hires. The results save to
Code:
empsNext,
Code:
json.dumps()Code:
empsCode:
json_strCode:
{"hires": [ { "ID": 3243, "name": "Alexa Smith", "title": "Manager" }, { "ID": 3244, "name": "Micah Jones", "title": "Designer" }, { "ID": 3245, "name": "Sam Quinn", "title": "Coder" } ]}
Note: The Code:
json.dumps()Code:
json.dump()Python Create JSON File and Write Data
This example writes a List of Dictionaries to a JSON file.
Code:
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
Code:
employees.jsonThe contents of this file is as follows:
Code:
{"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.
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 print(json_str)This code snippet opens, reads the
Code:
employees.jsonCode:
json_strCode:
\nCode:
replace()Once all lines have been read, the contents of
Code:
json_strPython Access JSON Elements
This example reads in the previously saved JSON file and accesses the ID element from each hire.
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)
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
Code:
employees.jsonCode:
json_strThen,
Code:
json_strCode:
json_loads()Code:
json_strThe following lines access the Employee IDs for Alexa and Micah and outputs same to the terminal.
Code:
3243 3245To iterate and display the
Code:
IDCode:
nameCode:
hireCode:
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:
Code:
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.
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)
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
[i]“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[/i]

