深度阅读

How to convert a Python dictionary to JSON?

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

In Python, you can use the json module to convert a Python dictionary to a JSON object. The json module provides two methods to do this: json.dumps() and json.dump().

Here’s an example using json.dumps():

import json

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

print(json_object)

This will output a string representation of the JSON object:

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

Alternatively, you can use json.dump() to write the JSON directly to a file:

import json

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

with open('output.json', 'w') as f:
    json.dump(my_dict, f)

This will write the JSON object to a file called output.json.

Note that the dictionary keys must be strings to be serialized in JSON format, and that the JSON format only supports a limited set of data types, including strings, numbers, booleans, lists, and dictionaries. If your dictionary contains custom objects or other data types, you will need to write custom serialization code to convert them to JSON.

相关标签

博客作者

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