![]() |
|
[Tut] Python Create JSON File - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Create JSON File (/thread-100181.html) |
[Tut] Python Create JSON File - xSicKxBot - 11-03-2022 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. 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 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]
|