【问题标题】:How to verify the structure of json?如何验证json的结构?
【发布时间】:2018-04-05 16:06:43
【问题描述】:

这是我的数据:

[{'DeviceInstanceId': 1, 'IsResetNeeded': False, 'ProductType': 'testing', 'Product': {'Family': '12345',"Model": "f10","Type": "data","Vendor": "qspi"}}]

我想验证结构、类型和键是否与下面的顺序相同,如果不是,我应该打印丢失的数据

'Product': {'Family': '12345',"Model": "f10","Type": "data","Vendor": "qspi"}

【问题讨论】:

  • 是否有特定的原因需要以相同的顺序输入键和输入。您可以创建一个模式并尝试读取 JSON。
  • 是的..我需要验证...你能告诉我如何创建架构
  • 您可以使用python-jsonschema.readthedocs.io/en/latest 来验证 JSON。
  • 你能告诉我如何创建架构...我是新手,所以...请

标签: json python-3.x schema


【解决方案1】:

假设这是你的 json 转换成 python 字典

ordered_dict = [{'DeviceInstanceId': 1, 'IsResetNeeded': False, 'ProductType': 'testing', 'Product': {'Family': '12345',"Model": "f10","Type ": "数据","供应商": "qspi"}}]

您可以使用ordered_dict.keys()按顺序获取所有键,现在由于它是字典列表,因此您必须获取所有项目的键并相互比较以检查所有键是否按顺序排列,我正在转换为元组的元组进行比较。

tuple_of_keys = tuple([tuple(j.keys()) for j in ordered_dict])

这将为您提供键元组的元组。

现在做一组像,

if len(set(tuple_of_keys)) == 1:
    print("all keys are in order")
else:
    print("missing data")

如果长度等于1,那么所有键的顺序相同

要比较产品密钥中的密钥,请将代码更改为

tuple_of_keys = tuple([tuple(j['Product'].keys()) for j in ordered_dict])

然后再次使用相同的方法

如果您想手动传递键的顺序并检查顺序是否匹配,请使用以下代码。

order_of_keys = ('Vendor', 'Model', 'Type', 'Family')

ordered_dict = [{'DeviceInstanceId': 1, 'IsResetNeeded': False, 
'ProductType': 'testing', 'Product': {'Family': '12345',"Model": 
"f10","Type": "data","Vendor": "qspi"}},{'DeviceInstanceId': 1, 
'IsResetNeeded': False, 'ProductType': 'testing', 'Product': {'Family': 
'12345',"Model": "f10","Type": "data","Vendor": "qspi"}}]


def tests(order_of_keys,ordered_dict):
    tuple_of_keys = tuple([tuple(j['Product'].keys()) for j in ordered_dict])
    for each_item in tuple_of_keys:
        if each_item == order_of_keys:
            print("all keys are in order")
        else:
            print("missing data")
tests(order_of_keys,ordered_dict)

【讨论】:

  • 我已对上述答案进行了更改,请检查
  • 当key order改变时,tuple项不匹配,set(tuple_of_keys)不等于1,你为什么不改变key的顺序,看看是否有效
  • 我在哪里可以通过我预期的键顺序...提交我的功能
  • 请参阅上面对答案的更改,使用更新的功能,让我知道这就是您要寻找的内容
  • 我可以得到你的邮件ID吗?
猜你喜欢
  • 2021-09-05
  • 2017-10-20
  • 2017-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多