推薦閱讀對象:
- 對於網路爬蟲有興趣的人
- 了解 json 的資料格式
我的閱讀動機:
- 網路時代帶來了數據爆炸的年代, 現在資料越來越多, 想要透過爬蟲的技術來幫助自己, 整理網路上的數據
- 想透過爬文的技術來做股市相關的分析
- 從新手開始, 學習Python 爬蟲
概述:
網路爬蟲常常使用到的格式, 與 python 的 dict 格式很像
JSON = javascript object notation
在進入爬蟲開發前, 先了解常用的資料格式
重點整理:
json 的資料格式
json 的資料格式有兩種:
1. 物件(object): 用大括弧表示 {}
2. 陣列(array): 用中刮鬍表示 []
物件說明:
規範:
- 一個物件內可以有多個配對資料
- 一個配對資料以 (key:value) 的方式配對儲存
- key 必須為字串, 字串格式以雙引號匡列, ""
- 值(value), 可以是數值、字串、布林值、陣列或 null
- json 文件內無註解
範例:
{"Name": "Joe", "age":30} => 一個物件, 有兩筆資訊, 名字為 Joe, 年齡30
{"testTime1st":15, "testTime2nd":5, "testTime3rd":1} => 一個物件, 有三筆資訊, 第一次測試時間為15, 第二次測試時間為5, 第三次測試時間為 1
陣列說明:
規範:
- 一個陣列可以有多筆資料, 以逗點隔開
- 純存資料格式有 object, string, number, array, bool, null
範例:
[{"Name": "Joe", "age":30} ,{"Name": "John", "age":20}, 2 ] => 一個陣列儲存三筆資料, 2個物件, 1個數字
[2, true, [{"Name":"Joe"},{"Name":"Amy"}]] => 一個陣列儲存三筆資料, 1個數字, 1個布林值, 1個陣列, 裡面的陣列存兩個物件
Json 與 Python 的格式轉換
應用 dumps() 將資料轉換成 json 格式
格式對照表
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
list 與 tuple 範例:
output
dict 範例:
output
dumps() 的 sort_keys 參數
可將轉成 json 的物件參考 key 做排序
sort_keys 範例:
output:
dumps() 的 indent 參數
json 是用一行字串顯示, 使用 indent 可以設定字串縮排
indent 範例:
output:
使用 load() 將 json 的格式資料轉成 Python 的資料
格式對照表
JSON | python |
---|---|
object | dict |
array | list |
string | unicode |
number(int) | int, long |
Number(real) | float |
true | True |
false | False |
null | None |
json 轉換 python 範例:
output:
json 文件與 json 物件
一個 json 文件只能有一個 json 物件, 這是設定好的規則, 若要將兩個物件放置一個文件內, 可以建立一個父物件, 加入兩個子物件, 達到此效果
Python 匯出與匯入 json 檔案
使用 open 與 dump() 將 Python 資料寫入 json 檔案
寫入範例:
output:
將中文資料轉換 json 檔案
若直接用上面的方法, 寫入中文字串, 文件上會顯示 16進位碼, python 內 json lib 預設支援格是為 ascii, 因此在此還進下使用中文, 要注意兩個地方:
1. open 時, 加上 encoding = 'utf-8' 的參數
2. 寫入動作, dump() 加入 ensure_ascii =False 的參數
寫入中文字範例:
output:
若未使用轉換 utf-8 的 output:
使用 load() 讀取 json 檔案
記得, 若是檔案內有中文, 在 open 的時候要加 encoding = 'utf-8'
load file 範例:
output:
Reference:
留言列表