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?

SORACOMのRemote Command (HTTP)でJSONを送信するときのTips

Posted at

TL;DR

  • SORACOM Flux で SORACOM API アクションを使って Remote Command 経由で
  • AI アクションが出力した JSON 文字列などをデバイスに JSON を送信するときは
  • JSON.stringify() した文字列をさらにもう一度エスケープしたものを渡すケースがある

この記事の目的

Remote Command (HTTP) で JSON をデバイスに送信するときにエスケープ処理が必要になりますが、ときどき何回エスケープする必要があるか分からなくなるので、備忘録として。

この記事では、下記のような JSON オブジェクトを Remote Command でデバイスに送信することを考えます。

[{"emoji_code":"1f4db","text":"Tofu on fire","display_mode":"center"}]

ユーザーコンソールから Remote Command

「ボディ」に送信したい JSON オブジェクトを書くだけでOKです。簡単ですね。

スクリーンショット 2025-08-28 16.36.16.png

Flux の SORACOM API アクションで Remote Command

ペイロードを手打ちする場合は、body フィールドにはデバイスに送信したい JSON オブジェクトを文字列化(JavaScript でいう JSON.stringify() )したものを渡す必要があります。

"body": "[{\"emoji_code\":\"1f4db\",\"text\":\"Tofu on fire\",\"display_mode\":\"center\"}]"

スクリーンショット 2025-08-28 20.19.55.png

また、AI アクションの出力を受け取って body に渡すようなユースケースの場合は、JSON.stringify() した文字列をさらにエスケープした文字列を生成して渡す必要があります。

"[{\\\"emoji_code\\\":\\\"1f4db\\\",\\\"text\\\":\\\"Tofu on fire\\\",\\\"display_mode\\\":\\\"center\\\"}]"

たとえば、前段の AI アクションで以下のようなプロンプトを書くと、output オブジェクト内にもとの JSON オブジェクトと、それを文字列化してエスケープした文字列が格納されることが期待されます(使用する AI モデルによっては適切に解釈してくれない場合があります)。

出力はかならず以下のフォーマットになるように生成してください。また、data を stringify し、その文字列に対してさらに `\"` を `\\\"` に置換した文字列を encoded_data フィールドとしてオブジェクトに含めてください。

出力例
\```
{
  "data": [
    {
      "emoji_code": "1f4db",
      "text": "Tofu on fire",
      "display_mode": "center"
    }
  ],
  "encoded_data": "[{\\\"emoji_code\\\":\\\"1f4db\\\",\\\"text\\\":\\\"Tofu on fire\\\",\\\"display_mode\\\":\\\"center\\\"}]"
}
`\\\

SORACOM API アクションでは 以下のような形で encoded_data をペイロードに含めることで、適切にデバイスに対して JSON ペイロードが送信されます。
スクリーンショット 2025-08-28 20.22.42.png

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?