Python Programming home
Department of Computing, Imperial College London
Python for C++ Programmers
Chapter 1: Introduction
Chapter 2: Basic data types
Chapter 3: Variables and operators
Chapter 4: Sequence types
Chapter 5: Sets and dictionaries
Chapter 6: Control flow
Chapter 7: Functions
Chapter 8: Object-oriented programming
Chapter 9: Modules
Chapter 10: Files
[10.1] Handling text files
[10.2] JSON files
[10.3] Loading JSON files
[10.4] Writing to JSON files
[10.5] pickle
[10.6] Pickling time!
[10.7] CSV files
[10.8] Reading CSV files
[10.9] Reading CSV files into a dict
[10.10] Writing to CSV files
[10.11] That's a wrap!
Chapter 10: Files
>> Writing to JSON files
face Josiah Wang
Conversely, you can also easily write a Python object to a JSON string. The fancy term is serialisation
(converting a data object into a string representation, usually for storage or transmission).
To write your data into a JSON file, use json.dump(). The following code serialises data to JSON format and saves it
in a file called output.json.
import json
data = {"course": "Introduction to Machine Learning", "term": 1}
with open("output.json", "w") as jsonfile:
json.dump(data, jsonfile)
To write your data to a string (and do something else with it later), use json.dumps().
json_string = json.dumps(data)
print(json_string) # {"course": "Introduction to Machine Learning", "term": 1}
Previous Next
Page designed by Josiah Wang Department of Computing | Imperial College London