• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

elm/json: Work with JSON in Elm

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

elm/json

开源软件地址:

https://github.com/elm/json

开源编程语言:

Elm 73.8%

开源软件介绍:

JSON in Elm

This package helps you convert between Elm values and JSON values.

This package is usually used alongside elm/http to talk to servers or ports to talk to JavaScript.

Example

Have you seen this causes of death table? Did you know that in 2002, war accounted for 0.3% of global deaths whereas road traffic accidents accounted for 2.09% and diarrhea accounted for 3.15%?

The table is interesting, but say we want to visualize this data in a nicer way. We will need some way to get the cause-of-death data from our server, so we create encoders and decoders:

module Cause exposing (Cause, encode, decoder)

import Json.Decode as D
import Json.Encode as E


-- CAUSE OF DEATH

type alias Cause =
  { name : String
  , percent : Float
  , per100k : Float
  }


-- ENCODE

encode : Cause -> E.Value
encode cause =
  E.object
    [ ("name", E.string cause.name)
    , ("percent", E.float cause.percent)
    , ("per100k", E.float cause.per100k)
    ]


-- DECODER

decoder : D.Decoder Cause
decoder =
  D.map3 Cause
    (D.field "name" D.string)
    (D.field "percent" D.float)
    (D.field "per100k" D.float)

Now in some other code we can use Cause.encode and Cause.decoder as building blocks. So if we want to decode a list of causes, saying Decode.list Cause.decoder will handle it!

Point is, the goal should be:

  1. Make small JSON decoders and encoders.
  2. Snap together these building blocks as needed.

So say you decide to make the name field more precise. Instead of a String, you want to use codes from the International Classification of Diseases recommended by the World Health Organization. These codes are used in a lot of mortality data sets. So it may make sense to make a separate IcdCode module with its own IcdCode.encode and IcdCode.decoder that ensure you are working with valid codes. From there, you can use them as building blocks in the Cause module!

Future Plans

It is easy to get focused on how to optimize the use of JSON, but I think this is missing the bigger picture. Instead, I would like to head towards this vision of data interchange.




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap