Im trying to write a small app that retrieves a JSON file (it contains a list of items, which all have some properties), saves its contents to the DB and then displays some of it later on. I have Zotonic up and running, and generating some HTML is no problem.
ATM i'm stuck trying to figure out how to define a custom resource and how to get the data from the JSON in the DB. When the data is there I should be fine, that part seems covered ok by the documentation.
I wrote some standalone erlang scripts that fetch the data and I noticed that Zotonic has a library for decoding JSON so that part should be fine. Any tips on where to put which code or where to look further?
Saving JSON data to DB in Zotonic
220 views Asked by g_uint At
1
There are 1 answers
Related Questions in JSON
- Handling both JSON and form values in POST request body with unknown values in Golang
- JSON Body is Not Passing Certain Strings
- Custom rewriter for json
- TypeScript: Type checking while parsing an arbitrary JSON that is typed/
- I dont understand what to do with: System.Text.Json.JsonException: 'The JSON value could not be converted to System.Collections.Generic.IEnumerable`1
- How to perform CRUD operations on a static JSON array in Angular? (without API)
- Dynamic Nested Multi-Dimensional Arrays in Rust
- Creating bar chart in FastAPI
- How to encode ttsJson data?
- Trying to get the id of the last element in my json file through an api
- How to give index id to my uploaded json file in FastAPI?
- JQ JSON - Values to Array
- Spring boot JSON parse error: Unexpected character error
- convert csv file with json data inside to a column, rows table in 2nd csv file
- Sigma.JS custom rendering
Related Questions in POSTGRESQL
- Only the first SQL script gets executed inside Docker Postgres container
- Compare fields in two tables
- Hibernate ClobJdbcType bindings: what are the diferences?
- Postgres && statement Error in Mybatis Mapper?
- Can this query be optimized? (Choosing a random row to insert, that excludes previously inserted Rows)
- Connection terminated unexpectedly while performing multi row insert using pg-promise
- Processing multiple forms in nodejs and postgresql
- How to copy data from SQLite to postgreSQL?
- PGAdmin4 configured behind a reverse proxy but unable to connect to Postgresql server
- Updates to pgsodium encrypted values don't use specified key_id
- Connecting to Postgres running in a Docker container using psql
- Can't connect to local postgresql server from my docker container
- Django Arrayfield migration to cloud sql (Postgresql) not creating the column
- Get list of matching keywords for each post
- docker-compose can't reset postgresql database
Related Questions in ERLANG
- Using gleam, cannot import 'gleam/otp/process'
- Zig Concurrency Vs Erlang Concurrency, is Zig less efficient than Erlang?
- Creaating a new Key Value dict from previous dict
- How to execute an exit function before closing rebar3 shell?
- rebar3 does not compile anything in `src` directory
- Ejabberd Migration from 23 to 24
- How to use compiled erlang modules in an elixir project?
- ejabberd_sql:handle_reconnect/2:491 odbc connection failed ejabberd
- Lisp Flavored Erlang: Can't find include lib include/ltest-macros.lfe
- Signing key for RabbitMQ
- Rabbitmq fails to start and getting Erlang eaacces error
- Erlang: binary_to_term explanation
- How to extend emqx clientInfo to get more fields during HTTP Authorization
- Transforming `erl_parse:abstract_form()` to `erl_syntax:syntaxTree()`
- Who is the sender of Erlang's trace messages and what can I assume based on it?
Related Questions in ZOTONIC
- Can't access internet from docker container
- Using GeShi with Zotonic CMS
- Saving JSON data to DB in Zotonic
- Is there a method for zotonic cms to replace some defined text parts to links?
- Zotonic: How to create HTML pages containing Javascript?
- Zotonic- where can a quickstart be found
- Is there a way to kill the erlang vm when it is running with -heart?
- How to embed and display Google Calendar in Zotonic the Erlang CMS
- jquery selector on ajax loaded content failing
- How to implement user registration with the Zotonic mod_signup module?
- How do you link to a media item by ID outside Zotonic?
- How do you loop through past items in a search in a Zotonic template?
- How do you provide download links for attached PDFs in Zotonic?
- How do you get third-level menu items in Zotonic?
- How do you control CSS styles from within the CMS interface in Zotonic?
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Popular Tags
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
The z_db module allows for creating custom tables by using:
The Table variable is your table name which can be either an atom or a list containing a single atom.
The Cols is a list of column definitions, which are defined by records. Currently the record definition (you can find this in include/zotonic.hrl) is:
See Erlang docs on records for more info on records
Example code which I put in users/sites/[sitename]/models/m_[sitename].erl:
Pay attention to what options of the record you specify. Most of the errors I got were e.g. from specifying a length on the integer fields.
The
models/m_sitename:init/1does not get called on site start. Thesitename:init/1does get called so I call the init function there to ensure the table exists. Example:It is called by Zotonic with the Context variable of the site automatically. You can get this variable manually as well with
z:c(sitename).. So if you call them_sitename:init(Context).from somewhere else you would do:Next, insertion in the DB can be done with:
Where Table is again an atom or a list containing a single atom representing the table name. Context is the same as above.
PropList is a property list which is a list containing tuples consisting of two elements where the first is an atom and the second is its associated value/property. Example:
See Erlang docs on Property Lists for more info on property lists.
=== The dependencies have been updated so if you build from source the step directly below is no longer needed ===
The JSON part is bit more tricky. Included with Zotonic are mochijson2 and as a secondary dependency also jiffy. The latest version of jiffy contains jiffy:decode/2 which allows you to specify maps as a return type. Much more readable than the standard
{struct, {struct, <<"">>}}monster. To update to the latest version edit the line indeps/twerl/rebar.configthat saysto
Now run
z:m().in the Zotonic shell. (you must do this after every change in your code).Now check in the Zotonic shell if there is a jiffy:decode/2 available by typing
jiffy: <tab>, it will show a list of available functions and their arity.To retrieve a JSON file from the internet run:
Which will yield the variable Body with the contents. See Erlang docs on http client for more info on this call.
Next convert the contents of Body to Erlang terms with:
What you have to do next depends a lot on the structure of your JSON resource. Keep in mind that everything is now in binary UTF-8 encoded strings! If you print JsonData to screen (just enter
JsonData.in your Zotonic/Erlang shell) you will see a lot of#map{<<"key"", <<"Value">>}this.My data was nested so I had to extract the needed data like this:
This gave me a list of maps, and in order to deal with them as individual items I used the following function:
As you might remember, the
z_db:insert/3function needs a property list to populate rows, so that what the call tomap_to_proplist/1is for. How this function looks is completely dependent on how your data looks but as an example here is what worked for me:See the documentation on string:to_list/1 as to why the tuples are needed when casting. The call to
m_sitename:insert_items(PropList,z:c(sitename))calls the z_db:insert/3 inmodels/m_sitename.erlbut wrapped in a catch:Ok, quite a long post but this should get you up and running if you were looking for this answer.
The above was done with Zotonic 0.13.2 on Erlang/OTP 18.
A repost (except the JSON part) of my post in the Zotonic Developers group.