4. 如何在不使用`json.dump()`或`json.dumps()`的情况下,手动将一个Python字典转换为JSON格式的字符串?请实现核心逻辑。
要将一个Python字典手动转换为JSON格式的字符串,可以按照以下步骤实现核心逻辑:
- 处理基本数据类型:Python中的基本数据类型(如整数、浮点数、字符串、布尔值和
None)可以直接映射为JSON中的对应类型。 - 处理复杂数据类型:对于字典和列表,需要递归处理其内部的元素。
- 转义字符串:JSON中的字符串需要转义特殊字符(如引号、换行符等)。
- 格式化输出:按照JSON的语法规则拼接结果字符串。
以下是一个详细的实现示例:
def dict_to_json(py_dict, indent=0):
result = []
indent_str = ' ' * indent
if isinstance(py_dict, dict):
result.append('{\n')
items = []
for key, value in py_dict.items():
key_str = f'"{escape_string(key)}": '
value_str = dict_to_json(value, indent + 4)
items.append(f'{indent_str} {key_str}{value_str}')
result.append(',\n'.join(items))
result.append(f'\n{indent_str}}}')
elif isinstance(py_dict, list):
result.append('[\n')
items = []
for item in py_dict:
items.append(f'{indent_str} {dict_to_json(item, indent + 4)}')
result.append(',\n'.join(items))
result.append(f'\n{indent_str}]')
elif isinstance(py_dict, str):
result.append(f'"{escape_string(py_dict)}"')
elif isinstance(py_dict, bool):
result.append('true' if py_dict else 'false')
elif py_dict is None:
result.append('null')
elif isinstance(py_dict, (int, float)):
result.append(str(py_dict))
else:
raise ValueError(f'Unsupported type: {type(py_dict)}')
return ''.join(result)
def escape_string(s):
escape_chars = {
'"': '\\"',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
for char, escaped in escape_chars.items():
s = s.replace(char, escaped)
return s
# 示例用法
example_dict = {
"name": "Alice",
"age": 30,
"is_student": False,
"scores": [95, 87, 91],
"address": {
"city": "New York",
"zip": "10001"
}
}
json_str = dict_to_json(example_dict, 0)
print(json_str)
输出结果:
{
"name": "Alice",
"age": 30,
"is_student": false,
"scores": [
95,
87,
91
],
"address": {
"city": "New York",
"zip": "10001"
}
}
关键点说明:
- 递归处理:
dict_to_json函数通过递归处理字典和列表中的嵌套结构。 - 类型检查:通过
isinstance检查数据类型,确保正确映射到JSON的对应类型。 - 字符串转义:
escape_string函数处理字符串中的特殊字符,确保生成的JSON字符串是合法的。 - 格式化:通过
indent参数控制缩进,使生成的JSON字符串具有良好的可读性。
通过这种方式,可以完全手动实现Python字典到JSON字符串的转换,而不依赖标准库的json模块。