# How to write a generic JSON decoder?

**URL:** <https://discourse.elm-lang.org/t/how-to-write-a-generic-json-decoder/3179>\
**Category:** Learn\
**Created:** [February 20, 2019, 2:03pm UTC](https://discourse.elm-lang.org/t/how-to-write-a-generic-json-decoder/3179 "2019-02-20T14:03:08Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![pdamoc](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/pdamoc/32/36_2.png) [@pdamoc](https://discourse.elm-lang.org/u/pdamoc)\
**Post date:** [February 21, 2019, 8:44am UTC](https://discourse.elm-lang.org/t/how-to-write-a-generic-json-decoder/3179/6 "2019-02-21T08:44:13Z")

</div>

What you can do is lift all the fields to strings.

```auto
module Main exposing (main)
 
import Html exposing (text)
import Json.Decode as Json 
import Dict

fromBool val = 
    if val then "True" else "False"

asString = 
    Json.oneOf 
        [ Json.string 
        , Json.map String.fromInt Json.int
        , Json.map String.fromFloat Json.float
        , Json.map fromBool Json.bool
        , Json.null ""
        ]

myDecoder = 
    Json.map3 (\name age powers -> {name=name, age = age, powers = powers} )
        (Json.field "name" Json.string)
        (Json.field "age" Json.int)
        powersDecoder
        
 
powersDecoder = 
    Json.map (Dict.filter (\k _ -> not (List.member k ["name", "age"]))) (Json.dict asString)  
 
 
inputJson = """
{
   "name": "rupert",
   "age": 42,
   "x-superpower": "teleportation",
   "x-king": true,
   "x-op": 9001
}
"""

main =
     text <| Debug.toString <| Json.decodeString myDecoder inputJson 

```

[link to Ellie](https://ellie-app.com/4MXCqnttprRa1)

Of course, this would not work for collection fields (arrays, objects) but you can extend `asString` to cover those cases if you need to.

---

_[View the full topic](https://discourse.elm-lang.org/t/how-to-write-a-generic-json-decoder/3179)._
