【笔记】2022.5.7 json

本文详细介绍了JSON数据格式及其在Python中的使用,包括JSON的格式要求、支持的数据类型,以及Python与JSON数据之间的转换方法。通过示例展示了如何使用Python的json模块将JSON数据转换为Python对象,以及如何将Python数据转换为JSON格式的字符串。同时,提供了从JSON文件中提取数据的两种方法:一种是使用json.loads,另一种是利用正则表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. json的作用

json是一种通用的数据格式,主要用于不同编程语言之间进行有效的数据交流

xml是另外一种通用的数据格式;json更小更快;xml更安全


2. json数据格式


2.1 json数据格式的要求

(1)一个json有且只有一个数据

(2)唯一的这个数据必须是json支持的数据类型的数据


2.2 json支持的数据类型

(1)数字:包括整数和小数,表示的时候直接写:28、2.3、3e5、-233

(2)字符串:双引号引起来的数据(支持转义字符):“abc”、“123”、“\tabc\n123\u4e00”

(3)布尔:只有true和false

(4)数组:相当于python列表:[元素1, 元素2, 元素3, …]

(5)字典:相当于python字典(键必须是字符串):{“键1”: 值1, “键2”: 值2, “键3”: 值3, …}

(6)空值:null


3. python数据和json数据之间的相互转换


3.1 json转python

jsonpython
数字int、float
字符串str(会将双引号变成单引号)
布尔true->True;false->False
空值null->None
数组list
字典dict

python中json模块包含了:loads、dumps

loads(json格式的字符串):将json数据转换成对应的python数据

说明:json格式的字符串:字符串内容是json数据的字符串(去掉字符串外面的引号后是一个合法的json数据)

WRONG Example:

result = loads('abc')	# 报错

RIGHT Example:

result = loads('"abc"')
print(result, type(result)) # abc <class 'str'>

result = loads('100')
print(result, type(result)) # 100 <class 'int'>

result = loads('true')
print(result, type(result)) # True <class 'bool'>

result = loads('[100, "abc", true]')
print(result, type(result)) # [100, 'abc', True] <class 'list'>

APPLICATION 得到json文件中的新闻标题:

# 方法1:loads函数
class ExtractJson:
    def __init__(self, text):
        self.text = text

    def title(self):
        from json import loads
        for news in loads(self.text)['newslist']:
            print(news['title'])


if __name__ == '__main__':
    text = open('data.json', 'r', encoding='utf-8').read()
    ex_json = ExtractJson(text)
    ex_json.title()


# 方法2:正则表达式
class ExtractJson:
    def __init__(self, text):
        self.text = text

    def title(self):
        from re import findall
        return findall(r'"title": "(.+?)",', self.text)


if __name__ == '__main__':
    text = open('data.json', 'r', encoding='utf-8').read()
    ex_json = ExtractJson(text)
    print(ex_json.title())

3.2 python转json

pythonjson
int、float数字
str字符串(会将单引号变成双引号)
boolTrue->true;False->false
NoneNone->null
list、tuple数组
dict字典

dumps(python数据):将指定的python数据转换成对应的json格式的字符串

RIGHT Example:

dumps(100)      # '100'
dumps('abc')    # '"abc"'
dumps(True)     # true
result = dumps({'a': 10, 20:'余婷', 'b':[1.23, False, None]})
print(result)   # {"a": 10, "20": "\u4f59\u5a77", "b": [1.23, false, null]}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Sprite.Nym

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

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

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

打赏作者

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

抵扣说明:

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

余额充值