如何在elm中将dict转换为JSON?或者有没有办法像JS中那样将dict字符串化


= Sku Internals

type alias Internals =
{ id : String --                    READONLY
, name : String --                  READ/WRITE
, imgExtras : ( List ImgExtra, String ) --      READ/WRITE
, availableSizes : List String --   READ/WRITE
}

如何将上面声明的字典值转换为JSON或字符串?

假设Dict实际上是指Internals记录,则应使用elm/JSON:将其编码为JSON对象

import Json.Encode as Encode
encodeInternals : Internals -> Encode.Value
encodeInternals internals =
Encode.object
[ ( "id", Encode.string internals.string )
, ( "name", Encode.string internals.name )
, ( "imgExtras", encodeImgExtras internals.imgExtras )
, ( "availableSizes", encodeAvailableSizes internals.availableSizes )
]
encodeImgExtras : (List ImgExtra, String) -> Encode.Value
encodeImgExtras (imgExtras, string) =
-- There's no equivalent of a tuple in JSON, so we encode it as an array. But you can of course choose any representation you'd like.
Encode.list
[ Encode.list encodeImgExtra imgExtras
, Encode.string string
]
encodeImgExtra : ImgExtra -> Encode.Value
encodeImgExtra imgExtra =
-- You'll need to implement this one yourself, as you haven't provided its definition.
...
encodeAvailableSizes : List String -> Encode.Value
encodeAvailableSizes availableSizes =
Encode.list Encode.string availableSizes

相关内容

  • 没有找到相关文章

最新更新