11

次の形式の JSON のスキーマを colander で定義するにはどうすればよいですか?

{
    'data' : {
        'key_1' : [123, 567],
        'key_2' : ['abc','def'],
        'frank_underwood' : [666.66, 333.333],
        ... etc ...
    }
}

「データ」内のキーは任意の文字列で、値は配列です。

現在、私は次のものを持っていますが、マッピングが持つことができる値の型に実際には何の制約もありません。

class Query(colander.MappingSchema):
    data = colander.SchemaNode(
        colander.Mapping(unknown='preserve'),
        missing={}
    )

これを説明する適切な方法は何ですか?

4

3 に答える 3

2

ザルについてはわかりませんが、Spyne を使用できます。

class Data(ComplexModel):
    key_1 = Array(Integer)
    key_2 = Array(Unicode)
    frank_underwood = Array(Double)

class Wrapper(ComplexModel):
    data = Data

完全な作業例: https://gist.github.com/plq/3081280856ed1c0515de

Spyne のモデル ドキュメント: http://spyne.io/docs/2.10/manual/03_types.html


ただし、それは必要なものではないことがわかりました。より大まかに指定された辞書が必要な場合は、カスタム型を使用する必要があります。

class DictOfUniformArray(AnyDict):
    @staticmethod  # yes staticmethod
    def validate_native(cls, inst):
        for k, v in inst.items():
            if not isinstance(k, six.string_types):
                raise ValidationError(type(k), "Invalid key type %r")
            if not isinstance(v, list):
                raise ValidationError(type(v), "Invalid value type %r")
            # log_repr prevents too much data going in the logs.
            if not len(set(map(type, v))) == 1:
                raise ValidationError(log_repr(v),
                                      "List %s is not uniform")
        return True

class Wrapper(ComplexModel):
    data = DictOfUniformArray

完全な作業例: https://github.com/arskom/spyne/blob/spyne-2.12.5-beta/examples/custom_type.py

于 2015-07-18T21:41:21.780 に答える
0

これが私が見つけた別の方法です。

from colander import SchemaType, Invalid
import json

class JsonType(SchemaType):
   ...
   def deserialize(self, node, cstruct):
    if not cstruct: return null
    try:
        result = json.loads(cstruct, encoding=self.encoding)
    except Exception as e:
        raise Invalid(node,"Not json ...")
    return result

colander で「タイプにとらわれない」SchemaNode を作成する方法

于 2015-07-23T16:49:36.630 に答える