finish up mqtt data format page

This commit is contained in:
brentru 2019-04-29 13:20:29 -04:00
parent 273da9cfb0
commit 328ef1cee6

View file

@ -113,3 +113,32 @@ Example of IO-Formatted JSON
It's worth noting that because Adafruit IO parses the entire JSON object that you send it, any valid JSON will be parsed and when it is stored in our system and forwarded to any subscribers, it will be regenerated. The significance of that is that if you publish JSON data with whitespace, it will be stored and republished without whitespace, because our generator produces the most compact JSON format possible.
### Double-Encoded JSON Strings
The second way you can send JSON data as a value is to "double encode" it before sending, in which case IO will treat it as a raw string.
If you're using something like javascript's `JSON.stringify` function or Ruby's `JSON.generate`, double encoding means passing the result of
`JSON.stringify` through `JSON.stringify` a second time. In this node.js console example, you can see the difference:
```
Example of sending double-encoding strings before sending through Adafruit IO
> JSON.stringify({"sensor-1":22.587,"sensor-2":13.182})
'{"sensor-1":22.587,"sensor-2":13.182}'
> JSON.stringify(JSON.stringify({"sensor-1":22.587,"sensor-2":13.182}))
'"{\"sensor-1\":22.587,\"sensor-2\":13.182}"'
```
The double encoded JSON string can be sent directly through Adafruit IO without interference from our processing system, because the processing system will not interpret it as JSON. In your receiving code, because the value passed through includes surrounding double quotes, you have to call your parse function twice to restore the JSON object.
```
Example of sending Double-Encoded JSON Strings directly through Adafruit IO
> var input = '"{\\\"sensor-1\\\":22.587,\\\"sensor-2\\\":13.182}"'
> JSON.parse(JSON.parse(input))
{ 'sensor-1': 22.587, 'sensor-2': 13.182 }
```
### Non-IO Formatted JSON
The third way you can send raw JSON data is to just send it. If Adafruit IO doesn't find a "value" key in the JSON object you send,
it will treat the whole blob as plain text and store and forward the data. That means with our example JSON object,
sending the string `{"sensor-1":22.587,"sensor-2":13.182}` will result in `{"sensor-1":22.587,"sensor-2":13.182}` being stored in IO and sent
to MQTT subscribers.