如何使用所有参数通过测试 a json 进行验证? Python
How can I validate with a test a json with all the parameters? Python
示例:
{ “名字”:“乔斯琳”,
“年龄”:30
}
和它 returns 一样。如果有人添加更多参数,它会失败。
我的理解是正确的,你可以写一个这样的函数(检查关键字)
import json
def check_json_data(json_str):
# base key list
base_keys = json.loads('{ "name": "Jocelyne", "age": 30 }').keys()
# convert json string to dict
input_json_data = json.loads(json_str)
# extract keys
input_keys = input_json_data.keys()
# check if there are additional keys in incoming keys
if set(input_keys) - set(base_keys): # for exact check of key list: set(input_keys) != set(base_keys)
return None
else:
return json_str
测试
print(check_json_data('{ "name": "Jocelyne", "age": 30, "age2": 30 }'))
print(check_json_data('{ "name": "Jocelyne", "age2": 30 }'))
print(check_json_data('{ "name": "Jose", "age": 33 }'))
None
None
{ "name": "Joce", "age": "33" }
示例: { “名字”:“乔斯琳”, “年龄”:30 } 和它 returns 一样。如果有人添加更多参数,它会失败。
我的理解是正确的,你可以写一个这样的函数(检查关键字)
import json
def check_json_data(json_str):
# base key list
base_keys = json.loads('{ "name": "Jocelyne", "age": 30 }').keys()
# convert json string to dict
input_json_data = json.loads(json_str)
# extract keys
input_keys = input_json_data.keys()
# check if there are additional keys in incoming keys
if set(input_keys) - set(base_keys): # for exact check of key list: set(input_keys) != set(base_keys)
return None
else:
return json_str
测试
print(check_json_data('{ "name": "Jocelyne", "age": 30, "age2": 30 }'))
print(check_json_data('{ "name": "Jocelyne", "age2": 30 }'))
print(check_json_data('{ "name": "Jose", "age": 33 }'))
None
None
{ "name": "Joce", "age": "33" }