iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 5
0
AI & Data

Scrapy爬蟲與資料處理30天筆記系列 第 5

[Day 05] JSON編碼解碼操作

嗨,今天是第五天啦,上一次說明了csv使用,今天來說說JSON (JavaScript Object Notation) 的編碼/解碼吧。

JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript [1] ).

上面為JSON的介紹,總之JSON是一種輕量級的數據交換格式也很好閱讀,就像是Python中的Dictionary一樣。

在開始之前當然要確定環境,安裝json這個套件:

  • (option) 啟用virtualenv
source path/to/your/virtualenv/bin/activate
  • 若是pip3則將pip改成pip3
pip install json

其實json套件,主要只有兩個函數要用,分別是:

  • json.dumps : 用來將Python的資料類型編成JSON格式。
  • json.loads : 將JSON物件轉為Python資料類型。

範例:

  • 建立一個dictionary資料,裡面包含name, height, weight 這三個Key的資料。
  • 透過dumps將這個dic轉成JSON的字串。
  • 將JSON字串轉回Python Dictionary格式。
import json

data = {
    'name' : 'plusone''',
    'height' : 155,
    'weight' : 40
}

jsonStr = json.dumps(data, sort_keys=True, indent=1)
print(jsonStr)

data = json.loads(jsonStr)
print(data)

參數:

  • sort_keys : 這個應該字面上很好理解了,是否排序Key。
  • indent : 若給非負整數,會幫你格式編排好看依照(填入的)數字等級。

可以比較兩者差異:

json_str = json.dumps(data, sort_keys=True, indent=5)
print(json_str)
# {
#      "height": 155,
#      "name": "plusone",
#      "someStr": [
#           {
#                "a": 123,
#                "b": 456
#           }
#      ]
# }

json_str = json.dumps(data, sort_keys=True, indent=1)
print(json_str)

# {
#  "height": 155,
#  "name": "plusone",
#  "someStr": [
#   {
#    "a": 123,
#    "b": 456
#   }
#  ]
# }

  • 基本上json編碼對Python而言幾乎沒有改變包含None, bool, int, float, str, list, tuple, dictionary
JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None
  • 比較特別的是true/Truefalse/False,而None則會轉為Null,例如:
data = {
    'one':True,
    'two':False,
    'three':None
}

json_str = json.dumps(data, indent=3)
print(json_str)

# output
# {
#    "one": true,
#    "three": null,
#    "two": false
# }

接著要說明pprint()這個套件。在loads()print()出來會很難閱讀,這時候可以使用pprint()

from pprint import pprint

data = {
    'one':True,
    'two':False,
    'three':
        {
        'text':[{'something': '2343488854324'},
            {'something': '2343453454354'}, 
            {'something': '1231242343545'},
            {'something': '3423423432113'}]
        }
}
# output
# {'one': True,
#  'three': {'text': [{'something': '2343488854324'},
#                     {'something': '2343453454354'},
#                     {'something': '1231242343545'},
#                     {'something': '3423423432113'}]},
#  'two': False}

若是用print()

# {'one': True, 'two': False, 'three': {'text': [{'something': '2343488854324'}, {'something': '2343453454354'}, {'something': '1231242343545'}, {'something': '3423423432113'}]}}

好的就是這樣,json就到這裡,今天說明了JSON的編碼解碼操作,也介紹了pprint讓資料顯示更美一點,明天見囉!

json — JSON encoder and decoder — Python 3.7.1rc1 documentation
pprint — Data pretty printer — Python 3.7.1rc1 documentation


上一篇
[Day 04] CSV 讀寫操作
下一篇
[Day 06] requests 發送HTTP請求
系列文
Scrapy爬蟲與資料處理30天筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言