Elm: Enter an alias for JSON with a type property

I have JSON with a type property that I want to import into Elm. for example, { "id": "abc", "type": "thing" } However, if I define a type alias with type as a property, the compiler complains. eg.

 type alias Foo = { id: String , type: String } 

produces

 It looks like the keyword `type` is being used as a variable. 3│ , type: String ^ Rename it to something else. 

Really? Do I need to rename a property? Is there no way to quote or run away from it so that it compiles?

+5
source share
4 answers

Yes, type is a reserved keyword and cannot be used as the name of a field in a record.

In Elm and Haskell, the most common task in your case is to add a single quote, so it becomes type' , and your type definition becomes

 type alias Foo = { id: String , type': String } 

This comes from the main character from mathematics. It may look odd at first, but it's syntax.

Then you can use the following Json Decoder to translate JSON to Foo:

 fooDecoder = Json.object2 Foo ("id" := Json.string) ("type" := Json.string) 

Note that the exact field name in Elm must not match the name of the JSON field.

You rarely find a language that allows you to use keywords as variable names without saving. This behavior is not unique to Elm.

+6
source

In oscpad, I use a type field in my json interface via websockets. But I don't have a field called a type in an elm record. I'm just looking for a type field when I parse JSON. My code is as follows:

 jsSpec : JD.Decoder Spec jsSpec = ("type" := JD.string) `JD.andThen` jsCs jsCs : String -> JD.Decoder Spec jsCs t = case t of "button" -> SvgButton.jsSpec `JD.andThen` (\a -> JD.succeed (CsButton a)) "slider" -> SvgSlider.jsSpec `JD.andThen` (\a -> JD.succeed (CsSlider a)) "label" -> SvgLabel.jsSpec `JD.andThen` (\a -> JD.succeed (CsLabel a)) "sizer" -> jsSzSpec `JD.andThen` (\a -> JD.succeed (CsSizer a)) _ -> JD.fail ("unkown type: " ++ t) 
+2
source

Now you can avoid the underlined keyword.

ex.

 type alias Foo = { id: String , type_: String } 
0
source

No exit. Elm is uncompromising.

-1
source

Source: https://habr.com/ru/post/1240997/


All Articles