Python 3:json 处理


#Python#


Python 的 json 库可以处理 json。

将list、dict转换为json字符串

示例1:基础示例

import json

data = {
    'name': '乐天',
    'scores': [99, 80, 82]
}

json_str = json.dumps(data)

print(json_str)

运行结果:

{"name": "\u4e50\u5929", "scores": [99, 80, 82]}

中文显示的是 unicode 代码,如果要显示中文,见下面的示例。

示例2:显示中文

指定 ensure_ascii 参数值为 False。

import json

data = {
    'name': '乐天',
    'scores': [99, 80, 82]
}

json_str = json.dumps(data, ensure_ascii=False)

print(json_str)

运行结果:

{"name": "乐天", "scores": [99, 80, 82]}

示例3:格式化输出

指定 indent 值即可。

import json

data = {
    'name': '乐天',
    'scores': [99, 80, 82]
}

json_str = json.dumps(data, indent=4, ensure_ascii=False)

print(json_str)

运行结果:

{
    "name": "乐天",
    "scores": [
        99,
        80,
        82
    ]
}

将 json 字符串转为为 Python 对象

使用 json.loads 方法。

示例:

import json

json_str = """
{
    "name": "乐天",
    "scores": [
        99,
        80,
        82
    ]
}
"""

data = json.loads(json_str)

print(type(data))
print()
print(data)

运行结果:

<class 'dict'>

{'name': '乐天', 'scores': [99, 80, 82]}

( 本文完 )