JSONLINT:python的json資料驗證庫執行個體解析,jsonlintjson

來源:互聯網
上載者:User

JSONLINT:python的json資料驗證庫執行個體解析,jsonlintjson

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式,易於人閱讀和編寫。

JSON 函數

使用 JSON 函數需要匯入 json 庫:import json。

函數 描述
json.dumps 將 Python 對象編碼成 JSON 字串
json.loads 將已編碼的 JSON 字串解碼為 Python 對象

隨著前後端分離和 REST APIs 的火熱,開發人員不斷尋找著一種靈活的、優雅的方式驗證 json 資料。有直接手動擷取資料驗證的,也有使用 json scheme 驗證的。前者容易使得函數變得冗長,還可能存在不少重複的驗證;後者驗證又不靈活。

本文介紹的 jsonlint 啟發自 python 的表單驗證工具 wtforms,wtforms 通過繼承 Form 類也能進行 json 資料驗證,但是 wtforms 對於 json 的數組(Array)類型處理有著很詭異的行為,需要通過 a-1 、 a-2 這樣來傳遞數組資料,常常不能有效處理數組資料。 jsonlint 大部分代碼來著 wtforms,可以視為 wtforms 的一個分支。但 jsonlint 刪去了 wtforms 的表單渲染部分,更改了傳入的資料格式,最重要的是使用正確的邏輯驗證數組(Array)和對象(Object)類型。下面是一些例子:

基本的字串類型json驗證

對於基本的字串類型,我們只需要建立一個 Json 的子類,填寫對應的 Field 即可。使用方式和 wtforms 類型:

from jsonlint import Jsonfrom jsonlint.fields import StringFieldfrom jsonlint.validators import DataRequiredclass MyLint(Json): name = StringField(validators=[DataRequired()])mylint = MyLint({'name': 'demo'})print mylint.validate() # Trueprint mylint.name.data # demo

更靈活的驗證 json 資料

jsonlint 繼承了 wtforms 的優點,可以進行一些更靈活的自訂json資料驗證,只要將 field 類的執行個體名寫成函數 validate_fieldname ,即可自訂驗證改欄位:

from jsonlint import Jsonfrom jsonlint.fields import IntegerFieldfrom jsonlint.validators import ValidationErrorclass AgeLint(Json): age = IntegerField() def validate_age(form, field):  if field.data < 13:   raise ValidationError("We're sorry, you must be 13 or older to register")agelint = AgeLint({'age': 12})print agelint.validate() # Falseprint agelint.age.errors # ["We're sorry, you must be 13 or older to register"]

對數群組類型進行驗證

jsonlint 誕生可以說主要就是為瞭解決如何驗證數群組類型的問題,在jsonlint這很容易實現:

from jsonlint import Jsonfrom jsonlint.fields import StringField, ListFieldfrom jsonlint.validators import DataRequired, ValidationErrorclass ListLint(Json): cars = ListField(StringField(validators=[DataRequired()])) def validate_cars(form, field):  if 'BMW' in field.data:   raise ValidationError("We're sorry, you cannot drive BMW")listlint = ListLint({'cars': ['Benz', 'BMW', 'Audi']})print listlint.validate() # Falseprint listlint.cars.errors # ["We're sorry, you cannot drive BMW"]

ListField 類作為一個 Field 容器,容納其它類型 Field 的數組,將對應類型的數組直接傳入,即可有效驗證;ListField 同樣也可以進行自訂驗證。

對物件類型進行驗證

物件類型在一些 REST APIs 的 web 應用中也經常存在,對此 jsonlint 也作了支援。只要將 Json 子類傳入 ObjectField 中即可進行驗證:

from jsonlint import Jsonfrom jsonlint.fields import ObjectField, IntegerField, BooleanFieldclass T(Json): status = BooleanField() code = IntegerField()class DataLint(Json): data = ObjectField(T)datalint = DataLint({'data': {'status': True, 'code': 200}})print datalint.validate() # Falseprint datalint.data.code.data # 200

寫在最後

jsonlint 誕生初衷就是因為本人想用類似 wtforms 的方式來驗證json,這樣不但有著良好的驗證方式,還可以分割業務,避免介面主函數變得十分冗長。例如,可以定義類:

class RegisterLint(UserLint): def validata_nickname(self, field):  ... def validate_account(self, field):  ... def create_user(self):  ...user = RegisterLint()

這樣既可以使用 RegisterLint 的執行個體 user 驗證資料,同時又能直接執行 user.create_user() 進行資料庫操作,將資料庫邏輯更好的封裝。這樣可以說是在 MVC 設計模式的基礎上獨立出了一層。

想要嘗試使用 jsonlint 可以直接使用 pip 安裝:

pip install jsonlint

最後,jsonlint 開源在 Github : https://github.com/tangwz/jsonlint

jsonlint 現階段僅由我一人維護,雖然單元測試覆蓋率儘可能的全覆蓋,但也不代表沒有bug,希望您提出您寶貴的意見,或一起維護、迭代jsonlint:

https://github.com/tangwz/jsonlint/issues

如果使用 Flask 進行 web 開發,也可以使用封裝好的結合了 Flask 和 jsonlint 的庫: Flask-Lint

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.