beatscode
Convert json to defstruct definition
I’m porting an application written in go to elixir. I’m just starting to learn elixir. In go it is easier to convert your data to structs to easily get properties from objects. I’d like to do the same in elixir. I’d like to convert a json payload to a set of defstructs. I see the docs on defstruct but I am wondering what developers do when the defstruct needed is too tedious to write. Are there any tools to convert a json payload to a defstruct definition?
I see the struct function but I would still need to write out the defstruct definition to make that function work. I am also using poison to convert the payload to a map but I’d like to use custom types instead.
Most Liked
NobbZ
I said, that I avoid creating defstruct only modules. If though I have related functions for some type, I do create a module and a defstruct as well. Thats it.
Also JSON doesn’t give you any guarantee about types, so why care?
Creating and maintaining depply nested structs is a burden and comes with a technical debt, when in fact all you need to rely on is the contract that there will be certain fields and you never care for the rest.
This is especially true when you have a JSON which constantly changes its shape and you need to find out the proper type first by checking a certain key in it.
OvermindDL1
If using Poison you can have it auto-convert a JSON string to a specific struct(s). You’d still need to write your structs, but once done then you have a confirmed structure.
NobbZ
Why do you need it to be a struct? Can’t you use a map instead?
I do usually try to avoid to create struct-only modules, so unless you do not want to create related functions, using a plain map might be so much easier.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








