Python3 使用技巧--json

Json 数据语法格式:

  • 键值对
  • 数据由逗号 , 分隔
  • 使用斜杆 \ 来转义字符
  • 大括号 {} 保存对象
  • 中括号 [] 保存数组,数组可以包含多个对象
  • 字符串用 “双引号”

JSON 值可以是:

  • 数字(整数或浮点数)
  • 字符串(在双引号中)
  • 逻辑值(true 或 false)
  • 数组(在中括号中)
  • 对象(在大括号中)
  • null

#!/usr/bin/python3
import json

# Python 字典类型转换为 JSON 对象
data = {
    'no': 1,
    'name': 'test',
    'flag': False
}

json_str = json.dumps(data)
# repr() 方法可以将读取到的格式字符,比如换行符、制表符,转化为其相应的转义字符。
print("Python 原始数据:", repr(data))
print("JSON 对象:", json_str)

# ****运行结果*****
Python 原始数据: {'no': 1, 'name': 'test', 'flag': False}
JSON 对象: {"no": 1, "name": "test", "flag": false}



# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print("data2['name']: ", data2['name'])
print("data2['flag']: ", data2['flag'])

# ****运行结果*****
data2['name']:  test
data2['flag']:  False

 读写json文件

# 写入 JSON 数据
with open('data.json', 'w') as f:
    json.dump(data, f)
 
# 读取数据
with open('data.json', 'r') as f:
    data = json.load(f)

中文处理:

# dict 转 json, dict中包含中文时 需要添加参数ensure_ascii=False
# 不加参数 中文会以Unicode格式表示{"\u660e\u5929": "\u5929\u6c14\u597d"}
json.dumps(new_logs, ensure_ascii=False)

# 写入文件
with open(write_path, "w", encoding='utf-8') as f:
    json.dump(all_res, f, ensure_ascii=False)



# 读取的json文件中有中文 encoding="utf-8"
with open(write_path, encoding="utf-8") as f:
    res = json.load(f)
    print(type(res))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值