python学习笔记(一)JSON

这篇博客介绍了Python中的JSON处理,包括JSON的基本概念、如何将Python数据类型转化为JSON以及JSON到Python的转换。主要关注json.dumps()方法在序列化过程中的应用。

python学习笔记(一)JSON

JSON是什么?

JSON 是用于存储和交换数据的语法。

怎样使用JSON?

JSON-——》python数据类型

import json
# 一些 JSON:
x =  '{ "name":"Bill", "age":63, "city":"Seatle"}'
# 解析 x:
y = json.loads(x)#对json类型进行解析
# 结果是 Python 字典:
print(y["age"])#63

python数据类型-——》JSON

import json

# Python 对象(字典):
x = {
  "name": "Bill",
  "age": 63,
  "city": "Seatle"
}
# 转换为 JSON:
y = json.dumps(x)
# 结果是 JSON 字符串:
print(y)#{"name": "Bill", "age": 63, "city": "Seatle"}

当 Python 转换为 JSON 时,Python 对象会被转换为 JSON不同类型

Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null

  • json.dumps()打印出来是一行,不容易读
json.dumps(x, indent=4)
  • 确认分割符号
json.dumps(x, indent=4, separators=(". ", " = "))
#{
    "name" = "Bill". 
    "age" = 63. 
    "married" = true. 
    "divorced" = false. 
    "children" = [
        "Jennifer". 
        "Rory". 
        "Phoebe"
    ]. 
    "pets" = null. 
    "cars" = [
        {
            "model" = "Porsche". 
            "mpg" = 38.2
        }. 
        {
            "model" = "BMW M5". 
            "mpg" = 26.9
        }
    ]
  • json.dumps() 方法提供了对结果中的键进行排序的参数:
json.dumps(x, indent=4, sort_keys=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Nefelibat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值