roc-json icon indicating copy to clipboard operation
roc-json copied to clipboard

[Feature request] Parse raw JSON

Open normanjaeckel opened this issue 11 months ago • 2 comments

I am looking for a way to delay JSON decoding. Go for example provides a special type called json.RawMessage and you can define a field of a struct with this, so unmarshaling JSON works with arbitrary content and it is possible to unmarshal the content later (like in this Go example).

RequestMessage : {
    name : Str,
    data : ??? # --> Here I need something like Json.RawMessage <--
}

jsonStr = Str.toUtf8 "{\"name\": \"Banana\", \"data\": {\"weight\": 42}}"

result1 : Result RequestMessage _
result1 =
    jsonStr |> Decode.fromBytes Json.json

BananaData : {
    weight : U64
}

OrangeData : {
    completlyDifferentFieldHere : Str
}

result2 =
    decodedValue <- Result.map result1

    if decodedValue.name == "Banana" then
        bananaData : Result BananaData _
        bananaData = 
            decodedValue.data |> Decode.fromBytes Json.json
        when bananaData is
            Ok bd -> bd.weight
            Err _ -> 0
    else if decodedValue.name == "Orange" then
        orangeData : Result OrangeData _ 
        ... # Try to decode orange data and calculate whatever makes sense here
    else
        crash "Oh no! No support for such fruits."

expect result2 == Ok 42

The sense is that I get different request messages (in this example). I want to decode the first part (name in this example) and according to the content I want to decode some other fields (data in this example).

I tried to use List U8 as magic type but this does not work.

So the feature request is that one can use such a nice type and the decoder parses the value as list of bytes e. g.

What do you think?

normanjaeckel avatar Mar 16 '24 00:03 normanjaeckel