前言:

        Json数据格式目前是非常流行的一种数据格式。python对Json有非常好的支持。

1. 导入模块

import json

2. 将 Python 对象转换为 JSON 字符串(json.dumps()

data = {
    "name": "Alice",
    "age": 30,
    "hobbies": ["reading", "cycling"]
}

json_str = json.dumps(data, indent=2)
print(json_str)

输出:

{
  "name": "Alice",
  "age": 30,
  "hobbies": [
    "reading",
    "cycling"
  ]
}

3. 将 JSON 字符串转换为 Python 对象(json.loads()

json_str = '{"name": "Bob", "age": 25, "hobbies": ["gaming", "hiking"]}'
data = json.loads(json_str)
print(data["name"])  # 输出: Bob

4. 从文件读取 JSON(json.load()

with open('data.json', 'r') as f:
    data = json.load(f)
print(data)

5. 将数据写入 JSON 文件(json.dump()

with open('output.json', 'w') as f:
    json.dump(data, f, indent=2)

6. 处理中文显示(避免转义)

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

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐