Let's Try Qiita API via curl of Ubuntu 20.04(WSL)
Let's Try Qiita API via curl of Ubuntu 20.04(WSL)
WSL(Ubuntu 20.04)のcurlでQiita APIを使ってみた。
powershellのときはpowershellのscriptだけで済んだが、
Let's try Qiita API v2 via curl of powershell - willwealth’s diary
シェルでJSONを扱うのは厳しそうだったので、外側にpythonをかぶせ python でdictに変換して処理した。
qiita.sh
#!/bin/bash url='https://qiita.com/api/v2/items?page=1&per_page=10' curl $url
powershellのcurlはcontentをStringで返してきたが、このケースでは'bytes'で返される。
>>> res = subprocess.run(['/home/user1/qiita.sh'],capture_output=True) >>> bs = res.stdout >>> type(bs) <class 'bytes'>
そこで、'bytes'をdecode()で'str'に変換してからjson.loads()する。
JSON文字列をdictに変換するloads()とは別に、ファイルからdictに変換するload()という関数があり躓いてしまった。
初心者からするとちょっと紛らわしかったので注意が必要だ。
qiita.py
#!/usr/bin/python3 import subprocess import json res = subprocess.run(['/home/user1/qiita.sh'],capture_output=True) bs = res.stdout str = bs.decode() arr = json.loads(str) for i,a in enumerate(arr): title = a['title'] print(f"[{i}] {title}")
了