Deepwalker / trafaret

Ultimate transformation library that supports validation, contexts and aiohttp.
http://trafaret.readthedocs.org/en/latest/
BSD 2-Clause "Simplified" License
177 stars 31 forks source link

JSON parsing #107

Closed Dreamsorcerer closed 4 years ago

Dreamsorcerer commented 4 years ago

It would be nice to have a way to automatically transform a JSON string before it is validated.

As an example:

token = t.Dict({
    "token": t.Dict({"access_token": t.String()}, json=True),
})

Where input might be something like:

token = {"token": "{\"access_token\": \"TOKEN\"}"}

Perhaps adding a json argument to the base trafaret would be useful, so any trafaret can be used with a JSON string.

Deepwalker commented 4 years ago

Trafaret main point is composability. So it is simple to do this:

def from_json(arg):
    try:
        return json.loads(arg)
    except ValueError:
        return t.DataError(code="bad_json", value=arg, message="Bad formed JSON string")

token = t.Dict({
    "token": t.String & from_json & t.Dict({"access_token": t.String()}),
})

Trafarets are monads with & as main compose function. So I encourage everyone to use monadic compose power for great good.

Dreamsorcerer commented 4 years ago

Ah, thanks for explaining how that'd work.