0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ショートカット.appの「URLの内容を取得」で長さが変わる辞書配列持ちJSONをPOSTする

Posted at

ショートカット.appから何らかのAPIを叩く際に、JSONをPOSTすることがあります。
そんなときは「URLの内容を取得」アクションを使ってJSONを投げるわけですが…スクリーンショット 2023-04-11 18.22.14.png
(このJSON編集がやたら落ちやすい、という問題はさておき)
この方法だと、JSONの要素の個数は固定されている必要があります。可変長のリストを変数として読み込ませても、うまく行きません。
例えば、the_list=[{"A":"aaa"},{"B":"bbb"}]というリストを上記アクションのkey="TEST", value=the_list的な気持ちで代入しても、{"test":["{\"A\":\"aaa\"}\n{\"B\":\"bbb\"}"]みたいな感じで、要素間が,ではなく改行だったり過剰にエスケープされてしまったりと、上手くいかない。
配列に自由が効かないということは、たとえば

{
  model:"gpt-3.5-turbo",
  temperature:7.5,
  messages:[
    {"role":"system", "content":"質問には140字以内で簡潔に答えてください。"},
    {"role":"user", "content":"私の名前は笠間哲史です。"},
    {"role":"assistant", "content":"こんにちは、笠間哲史さん。"},
    {"role":"user", "content":"私の名前はなんですか?"}
  ]
}

のような形式で、messages配列がどんどん伸びていくようなAPIを叩きたいとすると、「URLの内容を取得」アクションのJSON POSTではうまくいかない。

解決策:JSON文字列を作ってFileとしてPOST

仕方ないので、自力でJSON文字列を作っちゃいましょう。
送るコンテンツはヘッダーでContent-Type="application/json"になってるので、「URLの内容を取得」アクションの「本文を要求」を、JSONではなくFileにして、自分で組み立てたJSON文字列を渡せばOKです。例えば↓こんな感じ。
IMG_20EDB3719EBF-1.jpeg
これで配列の長さも中身も自由自在。
Enjoy!

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?