Many web services return data as JSON
JSON is a standard data format that can be intimidating at first glance.
Using a linting tool to format JSON makes it easier to read
JSON contains key pairs
"kay":"value"
{"kay":{"subkey0":"subvalue0","subkey1":"subvalue1,....."}}
{"key":[listvalue0,listvalue1,listvalue2,...]}
Basically what you'll notice is there's a pattern to how the JSON data looks.
To retrieve the value from a "key":"value" request the key name
print(results['requestId'])
To request a value from a {"kay":{"subkey0":"subvalue0","subkey1":"subvalue1,....."}} specify the key name and the subkey name
print(results['color']['dominantcolorbackground'])
To request a value from a {"kay":{"subkey0":"subvalue0","subkey1":"subvalue1,....."}} specify the keyname and index position of the value to retrieve
print(results['description']['tags'][0])
Use a loop to retreve all values from a {"key":[listvalue0,listvalue1,listvalue2,...]}
for item in results['description']['tags']:
print(item)
You can create "key":"value"JSON objects from a dictionary
#Create a dictionary object
person_dict = {'first':'Christopher','last':'Harrison'}
#Add additional key pairs as needed to dictionary
person_dict['City']='Seattle'
#Convert dictionary to JSON object
person_json = json.dumps(person_dict)
print(person_json)

注意先要import json
P39实操:
她视频里给的地址没权限,有时间自己找一个试试
本文介绍了JSON这种标准数据格式的基础知识,包括其三种主要结构:键值对、嵌套键值对和键值列表。通过使用linting工具格式化,可以更方便地阅读JSON。提取JSON中的值需要指定键名,对于嵌套结构,还需指定子键名。对于列表结构,可以使用循环获取所有值。此外,可以从字典创建JSON对象,但记得先导入json模块。

被折叠的 条评论
为什么被折叠?



