Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Writing to a JSON file
6. Convert a string into a JSON file


Why didn't that work? The JSON format does not have a representation for sets, so the json module does not know how to dump a Python set into JSON. If you want to save a set in JSON format, you have to choose one of the types supported by JSON: an array or a JSON object.

For now, let's move on. Suppose we want to save our data in a file. No problem – we simply use the json.dump() function. (Note: That's dump without an "s".) This function writes the data converted to its JSON representation into a file. Have a look:

with open('data.json', 'w') as outfile:
  json.dump(data, outfile)

Remember, json.dumps() converts the given data to a string. The json.dump() function writes that data to a specified file.


Save the data variable in JSON format to a file named personal_data.json.