【问题标题】:Need help defining key-value pairs in json schema需要帮助在 json 模式中定义键值对
【发布时间】:2023-01-11 11:53:33
【问题描述】:

我有一个 json,它有键:试图转换为 JSON 模式的值对。你能帮我如何为这两个键动态地获取值:值吗? [ 即:test、testa、testb、testc、testd:- 需要是动态的]

{"test" : {"content":{"testa" : "testb","testc" : "testd"}}}

谢谢你。

我已经尝试将 json 转换为 json 模式,但我无法动态添加“键”:“值”,而不是修复该键。

【问题讨论】:

    标签: arrays json object jsonschema key-value


    【解决方案1】:

    有一些库可用于在 Python 中将 JSON 转换为 JSON Schema,例如 jsonschema、json-schema-generator 和 json-schema-tools。将 JSON 对象转换为 JSON 模式的过程通常涉及创建 JSON 模式类的实例,然后递归遍历 JSON 对象以填充类的属性和属性。

    对于您提供的示例,生成 JSON 架构的一种方法是首先创建一个空白架构对象,然后遍历原始 JSON 对象中的键和值,并使用这些值动态填充架构的属性和属性目的。

    下面是一个示例,说明如何使用 jsonschema 库将 JSON 转换为 JSON 模式,假设 JSON 对象存储在名为 json_obj 的变量中:

    从 jsonschema 导入 Draft4Validator、FormatChecker 从 jsonschema.exceptions 导入 best_match

    def json_to_schema(json_obj): # 创建一个空的模式对象 架构= { "$schema": "http://json-schema.org/schema#", “类型”:“对象”, “特性”: {} }

    # Iterate over the keys and values in the JSON object
    for key, value in json_obj.items():
        # If the value is a nested JSON object, recursively convert it to a schema
        if isinstance(value, dict):
            schema["properties"][key] = json_to_schema(value)
        else:
            # Otherwise, add the key and value to the schema's properties
            schema["properties"][key] = {"type": "string"}
    
    return schema
    

    json_schema = json_to_schema(json_obj)

    这样,您就可以生成带有动态键的 JSON 模式,但请注意,这只是一个示例,可能需要根据您的实际用例和要求进行一些调整。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多