我有以下資料并想驗證它的值integer,float或者string
屬性::: id metric attribute::: name points attribute::: cake_name None attribute::: time None attribute::: time None ["key 'id'不是字串,得到 None”,“key 'metric' 不是整數,得到 <class 'str'>”,“key 'points' 不是整數,得到 <class 'NoneType'>”]
uj5u.com熱心網友回復:
我的解決方案是遞回解決方案,用于讀取嵌套的 json 資料。
from functools import partial
from typing import Union, Callable
import json
def get_output(key, val, string_keys: list, int_keys: list, float_keys: list):
out = None
if key in string_keys:
if not isinstance(val, str):
out = f"key '{key}' is not a string, got {type(val)}"
elif key in int_keys:
if not isinstance(val, int):
out = f"key '{key}' is not a integer, got {type(val)}"
elif key in float_keys:
if not isinstance(val, float):
out = f"key '{key}' is not a float, got {type(val)}"
return out
def explore_json(json: Union[dict, list], validator: Callable):
result = []
if isinstance(json, dict):
for key, val in json.items():
if isinstance(val, (dict, list)):
result.extend(explore_json(val, validator))
else:
out = validator(key, val)
if out is not None:
result.append(out)
elif isinstance(json, list):
for val in json:
result.extend(explore_json(val, validator))
return result
data = json.loads(json_data)
explore_json(data, validator)
validator = partial(get_output,
string_keys=["id", "name", "cake_name", "time"],
int_keys=['metric','points'],
float_keys=["LA:TB2342", "LA:TB2341", "LA:TB2344"])
data = json.loads(json_data)
explore_json(data, validator)
這個的輸出是:
["key 'id' is not a string, got <class 'NoneType'>",
"key 'metric' is not a integer, got <class 'str'>",
"key 'LA:TB2342' is not a float, got <class 'str'>"]
偏函式的先進之處在于我們可以為每個特定的 json 設定一個驗證器。
此外,請注意,只有string_keys, int_keys, float_keys在我們特定驗證器中定義的串列中的鍵才能在輸出串列中,任何不在這些串列中的鍵都不會被驗證。
最后,我不確定串列是否與您的相同,但只需更改它們并檢查輸出即可。
編輯用于跟蹤父鍵:
def explore_json(json: Union[dict, list], validator: Callable, parent_key=" parent_key:"):
result = []
if isinstance(json, dict):
for key, val in json.items():
if isinstance(val, (dict, list)):
#result = explore_json(val, validator, result)
result.extend(explore_json(val, validator, f"{parent_key}.{key}"))
else:
out = validator(key, val)
if out is not None:
if parent_key != " parent_key:":
out = parent_key
result.append(out)
elif isinstance(json, list):
for block_num, val in enumerate(json):
result.extend(explore_json(val, validator, f"{parent_key}.item{block_num}"))
# result = explore_json(val, validator, result)
return result
輸出:
["key 'id' is not a string, got <class 'NoneType'>",
"key 'metric' is not a integer, got <class 'str'>",
"key 'LA:TB2342' is not a float, got <class 'str'> parent_key:.anticipations.item1.top_properties"]
item1 表示錯誤在關鍵預期串列的第一個元素中
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507278.html
