How do I write JSON data stored in the dictionary data to a file? f = open('data.json', 'wb') f.write(data) This gives the error: TypeError: must be string or buffer, not dict

 

To write JSON data stored in a dictionary to a file in Python, you need to first convert the dictionary to a JSON-encoded string using the json module. Then, you can write the string to the file. The open function should be used with the mode 'w' (write) for text files. Here's how you can do it:

python
import json data = { "name": "John", "age": 30, "city": "New York" } # Convert the dictionary to a JSON-encoded string json_data = json.dumps(data) # Open the file in write mode and write the JSON data with open('data.json', 'w') as f: f.write(json_data)

In this example:

  1. The json.dumps() function is used to convert the data dictionary into a JSON-encoded string.
  2. The open() function is used with the mode 'w' to open the file in write mode. The with statement is used to ensure that the file is properly closed after writing.
  3. The JSON data is then written to the file using the write() method.

After running this code, a file named data.json will be created in the current working directory containing the JSON data from the dictionary.

Make sure you have the json module available (which is a standard library module in Python) by default. If you receive an error like "No module named 'json'", it might indicate an issue with your Python environment configuration.

Comments