7Grabbing JSON from some url is very easy.
9`strandio` includes the `fetch-json` function which will handle the HTTP request, response, and parsing, producing `json`.
11The following thread fetches the current Bitcoin price from the [CoinGecko
12API](https://www.coingecko.com/en/api) in the specified currency and prints it
20=, strand=strand:spider
22=, strand-fail=strand-fail:libstrand:spider
28 "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies="
29=/ cur !<((unit @tas) arg)
30?~ cur (strand-fail %no-arg ~)
31=. u.cur (crip (cass (trip u.cur)))
32?. ((sane %tas) u.cur) (strand-fail %bad-currency-format ~)
33;< =json bind:m (fetch-json (weld url (trip u.cur)))
34=/ price=(unit @ta) ((ot ~[bitcoin+(ot [u.cur no]~)]) json)
35?~ price ((slog 'Currency not found.' ~) (pure:m !>(~)))
36%- (slog leaf+"{(trip u.price)} {(cuss (trip u.cur))}" ~)
40Save it as `/ted/btc-price.hoon` in the `%base` desk of a fake ship, `|commit %base` and run it with `-btc-price %usd`. You should see something like:
47You can try with other currencies as well:
60The thread takes an `@tas` as its argument, which the dojo wraps in a `unit`. We extract the `vase` and check it's not empty:
63=/ cur !<((unit @tas) arg)
64?~ cur (strand-fail %no-arg ~)
67We then convert it to lowercase and check it's a valid `@tas`:
70=. u.cur (crip (cass (trip u.cur)))
71?. ((sane %tas) u.cur) (strand-fail %bad-currency-format ~)
74Next, we use the `fetch-json` function in `strandio` like so:
77;< =json bind:m (fetch-json (weld url (trip u.cur)))
80We convert the currency to a `tape` and `weld` it to the end of the `url`, which
81we give as an argument to `fetch-json`. The `fetch-json` function will make the
82request to the URL, receive the result, parse the JSON and produce the result as
85The JSON the API produces looks like:
95Since it's an object in an object, we decode them using nested
96[`ot:dejs-soft:format`](/docs/hoon/reference/zuse/2d_7#otdejs-softformat)
97functions, and the price itself using
98[`no:dejs-soft:format`](/docs/hoon/reference/zuse/2d_7#nodejs-softformat) to
99produce a `(unit @ta)`:
102=/ price=(unit @ta) ((ot ~[bitcoin+(ot [u.cur no]~)]) json)
105Finally, we check if the `unit` is null and either print an error or print the price to the terminal with `slog` functions (the thread itself produces `~`):
108?~ price ((slog 'Currency not found.' ~) (pure:m !>(~)))
109%- (slog leaf+"{(trip u.price)} {(cuss (trip u.cur))}" ~)
113For more information about working with `json`, see the [JSON
114Guide](/docs/hoon/guides/json-guide).
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list