文章目录
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
json | python |
---|---|
数字 | 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
python | json |
---|---|
int、float | 数字 |
str | 字符串(会将单引号变成双引号) |
bool | True->true;False->false |
None | None->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]}