Snatch any course you want for just $15! Go to “Courses” and find a course ↓
Introduction
Writing to a JSON file
6. Convert a string into a JSON file
Summary

Instruction

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.

Exercise

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