Skip to content

Instantly share code, notes, and snippets.

@scarf005
Created April 19, 2025 12:09
Show Gist options
  • Save scarf005/ccaf43fd6da9b443cb0ace375e7dca6b to your computer and use it in GitHub Desktop.
Save scarf005/ccaf43fd6da9b443cb0ace375e7dca6b to your computer and use it in GitHub Desktop.
order preserving javascript JSON serde via giving and passing Map
use serde_json::Value;
use serde_wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn parse_json(string: JsValue) -> Result<JsValue, JsValue> {
let string: String = string
.as_string()
.ok_or_else(|| JsValue::from_str("Expected a string"))?;
let string: Value = serde_json::from_str(&string)
.map_err(|e| JsValue::from_str(&format!("Failed to parse JSON: {}", e)))?;
let js_value = serde_wasm_bindgen::to_value(&string).map_err(|e| {
JsValue::from_str(&format!("Failed to serialize to JsValue: {e}"))
})?;
Ok(js_value)
}
#[wasm_bindgen]
pub fn stringify_json(value: JsValue) -> Result<JsValue, JsValue> {
let value: Value = serde_wasm_bindgen::from_value(value)
.map_err(|e| JsValue::from_str(&format!("Failed to deserialize from JsValue: {e}")))?;
let string = serde_json::to_string_pretty(&value)
.map_err(|e| JsValue::from_str(&format!("Failed to serialize to JSON: {e}")))?;
Ok(JsValue::from_str(&string))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment