深度阅读

How to convert dictionary to JSON in Python

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

To convert a dictionary to JSON in Python, you can use the json.dumps() function from the built-in json module. This function takes a Python object (such as a dictionary) as input and returns a JSON-formatted string.

Here’s an example:

import json

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

print(my_json)   # Output: {"name": "John", "age": 30, "city": "New York"}

In this example, we define a dictionary my_dict containing some key-value pairs. We use the json.dumps() function to convert the dictionary into a JSON-formatted string called my_json. The resulting string is equivalent to the original dictionary contents, but in JSON format.

Note that the json.dumps() function can also take additional parameters to customize the JSON output, such as specifying the indentation level or handling non-ASCII characters.

In general, converting a dictionary to JSON can be useful when you need to transfer or store the dictionary data in a standardized, text-based format.

博客作者

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