[elm-discuss] Re: Json.Decode list of objects without known fields

2016-09-16 Thread Oliver Searle-Barnes
You can do this with a Dict but it's a little fiddly because you need to 
use an ADT to represent the different types of the values

import Html
import Json.Decode as JD
import Dict
import String


json : String
json =
 """
 [{"a": 1, "foo": "bar", "bar": "baz"},
 {"a": 2, "foo": "baz", "bar": "foo"},
 {"a": 34, "foo": "big", "bar": "lebowski"}]
 """


type ValueType = StringType String | IntType Int


valueTypeDecoder =
  JD.oneOf
[ JD.map StringType JD.string
, JD.map IntType JD.int
]


gen_keys : String -> String
gen_keys json =
json
|> JD.decodeString (JD.list <| JD.dict valueTypeDecoder)
|> Result.toMaybe
|> flip Maybe.andThen List.head
|> Maybe.map Dict.keys
|> Maybe.withDefault []
|> String.join ","


main : Html.Html string
main =
Html.text (gen_keys json)


On Saturday, 17 September 2016 00:52:20 UTC+2, Gary Young wrote:
>
> In short.  Solve this:
>
> module Main exposing (..)
>
> import Html
>
>
> -- import Json.Decode exposing (Decoder, decodeString, keyValuePairs)
>
>
> json : String
> json =
> """[{a: 1, foo: "bar", bar: "baz"},
>  {a: 2, foo: "baz", bar: "foo"},
>  {a: 34, foo: "big", bar: "lebowski"}]"""
>
>
> gen_keys : String -> String
> gen_keys json =
> -- Decode the first JSON record and return a comma separated
> -- list of keys
> json
>
>
> main : Html.Html string
> main =
> Html.text (gen_keys json)
>
>

-- 
You received this message because you are subscribed to the Google Groups "Elm 
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elm-discuss+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[elm-discuss] Re: Json.Decode list of objects without known fields

2016-09-16 Thread Gary Young
In short.  Solve this:

module Main exposing (..)

import Html


-- import Json.Decode exposing (Decoder, decodeString, keyValuePairs)


json : String
json =
"""[{a: 1, foo: "bar", bar: "baz"},
 {a: 2, foo: "baz", bar: "foo"},
 {a: 34, foo: "big", bar: "lebowski"}]"""


gen_keys : String -> String
gen_keys json =
-- Decode the first JSON record and return a comma separated
-- list of keys
json


main : Html.Html string
main =
Html.text (gen_keys json)

-- 
You received this message because you are subscribed to the Google Groups "Elm 
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elm-discuss+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.