Serialization Without Crates
JSON-Shaped Record
Escape Text Fields
A JSON-shaped string needs quotes around text fields and escaping before data is embedded.
Program
Play the program to choose a name and build a small JSON-shaped record with a fixed score.
json_like_record.rs
fn main() {
let name = ;
let score = 7;
let record = json_record(name, score);
println!("{record}");
}
fn json_record(name: &str, score: i32) -> String {
format!("{{\"name\":\"{}\",\"score\":{score}}}", escape_json(name))
}
fn escape_json(text: &str) -> String {
text.replace('\\', "\\\\").replace('"', "\\\"")
}
fn main() {
let name = ;
let score = 7;
let record = json_record(name, score);
println!("{record}");
}
fn json_record(name: &str, score: i32) -> String {
format!("{{\"name\":\"{}\",\"score\":{score}}}", escape_json(name))
}
fn escape_json(text: &str) -> String {
text.replace('\\', "\\\\").replace('"', "\\\"")
}
fn main() {
let name = ;
let score = 7;
let record = json_record(name, score);
println!("{record}");
}
fn json_record(name: &str, score: i32) -> String {
format!("{{\"name\":\"{}\",\"score\":{score}}}", escape_json(name))
}
fn escape_json(text: &str) -> String {
text.replace('\\', "\\\\").replace('"', "\\\"")
}
JSON-shaped text
The output follows a simple JSON object shape for this fixed record.
escaping
`escape_json` protects text before embedding it between quotes.
crate boundary
This example shows the concept without adding an external serialization crate.