JSON Formatter

This is a bot for formatting JSON. This bot will return a formatted JSON string when a user sends an unformatted JSON string.


#![allow(unused)]
fn main() {
use wasm_bindgen::prelude::*;
use serde_json::{Value};

#[wasm_bindgen]
pub fn text_received(msg: String, _user_info: String, _step_data: String) -> String {
  let obj: Value = match serde_json::from_str(&msg) {
    Ok(v) => v,
    Err(e) => return format!("{:?}", e)
  };
  let str = serde_json::to_string_pretty(&obj).unwrap();
  return format!(r#"{{"result": "{}"}}"#, str.replace("\"", "\\\""));
}
}

The bot uses serde_json to format JSON strings. There is no need for too much code.

One thing to be noted is that you should not return the JSON string directly, but should return it as { "result": "JSON string to return" }. Only in this way can the Host parse out the correct content to return.

Furthermore, the code did not use _step_data because there is no need to cache previous chat messages. The only message that matters is the last message sent by the user that contains an unformatted JSON.