python json数据描述,使用python验证JSON数据

I’m pretty new in python so would you be so kind to help me? It seems to be really trivial question.

I need to create a function that validates incoming json data and returns python dict. It should check if there all necessary fields present at json file and also validate data types of that fields. I need to use try-catch. Could you provide some kind of snippets or examples that give me answers?

解决方案

If you haven't check jsonschema library, it can be useful to validate data. JSON Schema is a way to describe the content of JSON. The library just uses the format to make validations based on the given schema.

I made a simple example from basic usage.

import json

from jsonschema import validate

# Describe what kind of json you expect.

schema = {

"type" : "object",

"properties" : {

"description" : {"type" : "string"},

"status" : {"type" : "boolean"},

"value_a" : {"type" : "number"},

"value_b" : {"type" : "number"},

},

}

# Convert json to python object.

my_json = json.loads('{"description": "Hello world!", "status": true, "value_a": 1, "value_b": 3.14}')

# Validate will raise exception if given json is not

# what is described in schema.

validate(instance=my_json, schema=schema)

# print for debug

print(my_json)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值