JSON (JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。它基于ECMAScript的一個子集。
Python3 中可以使用 json 模塊來對 JSON 數(shù)據(jù)進行編解碼,它包含了兩個函數(shù):
json.dumps(): 對數(shù)據(jù)進行編碼。
json.loads(): 對數(shù)據(jù)進行解碼。
import json
#Python 字典類型轉(zhuǎn)換為 JSON 對象
data = {
'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data)
print ("Python 原始數(shù)據(jù):", repr(data))
print ("JSON 對象:", json_str)
Python 原始數(shù)據(jù): {'url': 'http://www.runoob.com', 'no': 1, 'name': 'Runoob'}
JSON 對象: {"url": "http://www.runoob.com", "no": 1, "name": "Runoob"}
import json # 加載json模塊
data = { # 定義一個字典類型
'a': 1,
'b': 2,
}
json_str = json.dumps(data) # 把字典類型轉(zhuǎn)化為字符串類型
print(json_str) # 打印字符串
print(type(json_str)) # 打印類型
data = '{"c": 3, "a": 1, "b": 2}' # 定義一個字符串類型
json_data = json.loads(data) # 把字符串類型轉(zhuǎn)化成字典類型
print(json_data) # 打印字典
print(type(json_data)) # 打印類型
import json
#Python 字典類型轉(zhuǎn)換為 JSON 對象
data1 = {
'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data1)
print ("Python 原始數(shù)據(jù):", repr(data1))
print ("JSON 對象:", json_str)
#將 JSON 對象轉(zhuǎn)換為 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])
案例爬取douban 數(shù)據(jù)
import requests
import json
#1、請求json 整體接口數(shù)據(jù)
for i in range(0, 100, 50):
url = "https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=0&limit="+format(i)
response = requests.get(url)
print("正在抓取網(wǎng)址" + url)
if response.text == [ ]:
print("=====抓取結(jié)束===")
#print(response.text)
#json.loads(): 對數(shù)據(jù)進行解碼。
py_date = json.loads(response.text)
#print(py_date)
#2、抽取想要數(shù)據(jù)
for i in py_date:
items = {"電影名稱": i['title'], "電影評分": i['score'], "上映地區(qū)": i['regions'], "鏈接圖片": i['cover_url'], "電影url": i['url']}
# json.dumps(): 對數(shù)據(jù)進行編碼。
content = json.dumps(items, ensure_ascii=False) + ",\n"
# print(content)
#3、 保成數(shù)據(jù)
with open("douban.json", "a", encoding="utf-8") as f:
f.write(content)
python3解析json格式中文亂碼 嘗試
encode(‘utf-8’).decode(‘utf-8’)
還是不行,給個解決辦法吧
encode(‘utf-8’).decode(‘unicode_escape’)
https://www.runoob.com/python3/python3-json.html
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
