深度阅读

How To Convert Python Dictionary To JSON?

作者
作者
2023年08月22日
更新时间
11.97 分钟
阅读时间
0
阅读量

To convert a Python dictionary to JSON, you can use the built-in json module in Python. The json.dumps() function can convert a Python dictionary to a JSON string. Here’s an example:

import json

my_dict = {'name': 'John', 'age': 30, 'city':'New York'}
json_string = json.dumps(my_dict)

print(json_string)

This will output:

{"name": "John", "age": 30, "city": "New York"}

In this example, we first import the json module, and then create a dictionary my_dict with some key-value pairs. Then, we use the json.dumps() function to convert the dictionary to a JSON string. Finally, we print the JSON string.

Note that json.dumps() returns a string, not a file. If you want to write the JSON to a file, you can open the file in “write” mode and use the json.dump() function instead:

import json

my_dict = {'name': 'John', 'age': 30, 'city':'New York'}
with open('my_file.json', 'w') as f:
    json.dump(my_dict, f)

In this example, we open the file my_file.json in “write” mode using the with statement. Then, we use the json.dump() function to write the dictionary to the file in JSON format. The resulting file will contain the JSON data.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。