榆树 - 用动态键解码Json

时间:2018-01-05 06:09:31

标签: json dictionary dynamic decode elm

我想要解码一个看起来像这样的Json文件:

{ 'result': [
    {'id': 1, 'model': 'online', 'app_label': 'some_app_users'}, 
    {'id': 2, 'model': 'rank', 'app_label': 'some_app_users'}, 
]}

或者像这样:

{ 'result': [
    {'id': 1, 'name': 'Tom', 'skills': {'key': 'value', ...}, {'key': 'value', ...}},
    {'id': 1, 'name': 'Bob', 'skills': {'key': 'value', ...}, {'key': 'value', ...}},
]}

基本上,result下的内容是一个具有相同键的词典列表 - 但我事先并不知道这些键,我不知道它们的值类型(int,string,dict等)。

目标是显示数据库表格内容; Json包含SQL查询的结果。

我的解码器看起来像这样(不编译):

tableContentDecoder : Decode.Decoder (List dict)
tableContentDecoder =
    Decode.at [ "result" ] (Decode.list Decode.dict)

我这样用:

Http.send GotTableContent (Http.get url tableContentDecoder)

我收到了这个错误:

  

函数list期望参数为:       Decode.Decoder(Dict.Dict String a)

     

但它是:       Decode.Decoder a - > Decode.Decoder(Dict.Dict String a)

使用dict解码器的正确语法是什么?那会有用吗?我找不到任何通用的Elm解码器......

2 个答案:

答案 0 :(得分:4)

Decode.list是一个函数,它接受Decoder a类型的值并返回类型Decoder (List a)的值。 Decode.dict也是一个函数,它采用类型为Decoder a的值,返回Decoder (Dict String a)的解码器。这告诉我们两件事:

  • 我们需要先将解码器值传递给Decode.dict,然后再将其传递给Decoder.list
  • Dict可能不适合您的用例,因为Dicts只能在两种固定类型之间进行映射,并且不支持'skills': {'key': 'value', ...}等嵌套值
榆树没有提供通用解码器。这样做的动机与Elm保证"没有运行时错误"有关。在与外界打交道时,Elm需要保护其运行时免受外部故障,错误等的影响。榆树的主要机制是类型。 Elm只允许正确描述其中的数据,这样做可以消除通用解码器引入错误的可能性。

由于您的主要目标是显示内容,Dict String String之类的内容可能会有效,但这取决于您的数据嵌套程度。您可以通过对代码进行少量修改来实现此目的:Decode.at [ "result" ] <| Decode.list (Decode.dict Decode.string)

另一种可能性是使用Decode.valueDecode.andThen来测试指示我们正在读取哪个表的值。

重要的是我们的解码器具有单一的一致类型,这意味着我们需要将可能的结果表示为和类型。

-- represents the different possible tables
type TableEntry
    = ModelTableEntry ModelTableFields
    | UserTableEntry  UserTableFields
    | ... 

-- we will use this alias as a constructor with `Decode.map3`
type alias ModelTableFields =
    { id       : Int
    , model    : String
    , appLabel : String
    }

type alias UserTableFields =
    { id : Int
    , ...
    }

tableContentDecoder : Decoder (List TableEntry)
tableContentDecoder =
    Decode.value 
        |> Decode.andThen 
            \value ->
                let
                    tryAt field = 
                        Decode.decodeValue
                            (Decode.at ["result"] <| 
                                Decode.list <|
                                Decode.at [field] Decode.string)
                            value
                in  
                    -- check the results of various attempts and use
                    -- the appropriate decoder based on results
                    case ( tryAt "model", tryAt "name", ... ) of
                        ( Ok _, _, ... ) ->
                            decodeModelTable

                        ( _, Ok _, ... ) ->
                            decodeUserTable

                        ...

                        (_, _, ..., _ ) ->
                            Decode.fail "I don't know what that was!"

-- example decoder for ModelTableEntry
-- Others can be constructed in a similar manner but, you might
-- want to use NoRedInk/Json.Decode.Pipline for more complex data
decodeModel : Decoder (List TableEntry)
decodeModel  =
    Decode.list <|
       Decode.map3 
           (ModelTableEntry << ModelTableFields)
           (Decode.field "id" Decode.int)
           (Decode.field "model" Decode.string)
           (Decode.field "app_label" Decode.string) 

decodeUser : Decoder (List TableEntry)
decodeUser = 
    ...

可以公平地说,这比大多数其他语言更能解析JSON。但是,这样做的好处是能够使用外部数据而不必担心异常。

一种思考方式是Elm让你提前完成所有工作。其他语言可能会让您更快地启动和运行,但请尽量减少以帮助您实现稳定的实施。

答案 1 :(得分:0)

我无法弄清楚如何让Decode.dict工作,所以我改变了我的Json并拆分了列和结果:

data={
    'columns': [column.name for column in cursor.description],
    'results': [[str(column) for column in record] for record in cursor.fetchall()]
}

我还必须将所有结果转换为String以使其变得简单。例如,Json将有'id': "1"

随着Json这样做,Elm代码非常简单:

type alias QueryResult =
    { columns : List String, results : List (List String) }

tableContentDecoder : Decode.Decoder QueryResult
tableContentDecoder =
    Decode.map2
        QueryResult
        (Decode.field "columns" (Decode.list Decode.string))
        (Decode.field "results" (Decode.list (Decode.list Decode.string)))
相关问题