Working with JSON
serde_json.
Working with JSON is a free Learn Rust Coding lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The serde_json crate
serde_json is the JSON format implementation for serde. It provides functions to convert between Rust values and JSON text.
to_string/from_strfor textValuefor dynamic JSON
Struct to JSON string
serde_json::to_string serializes any Serialize value to a JSON string.
use serde::Serialize;
#[derive(Serialize)]
struct User { id: u32, name: String }
fn main() {
let u = User { id: 1, name: "Alice".to_string() };
let json = serde_json::to_string(&u).unwrap();
println!("{}", json);
}JSON string to struct
serde_json::from_str parses JSON into a typed value, returning a Result so you can handle malformed input.
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct User { id: u32, name: String }
fn main() {
let data = r#"{"id":1,"name":"Alice"}"#;
let u: User = serde_json::from_str(data).unwrap();
println!("{:?}", u);
}Pretty printing
Use to_string_pretty for human-readable, indented JSON, handy for config files and debugging.
use serde::Serialize;
#[derive(Serialize)]
struct Cfg { debug: bool, level: u8 }
fn main() {
let c = Cfg { debug: true, level: 3 };
println!("{}", serde_json::to_string_pretty(&c).unwrap());
}The json! macro
Build JSON inline with the json! macro, which produces a Value without defining a struct.
use serde_json::json;
fn main() {
let v = json!({
"name": "Alice",
"roles": ["admin", "user"]
});
println!("{}", v);
}The Value type
serde_json::Value is an enum representing any JSON node: null, bool, number, string, array, or object. Use it when the shape is unknown.
use serde_json::Value;
fn main() {
let data = r#"{"name":"Bob","age":30}"#;
let v: Value = serde_json::from_str(data).unwrap();
println!("{}", v["name"]);
println!("{}", v["age"]);
}Safely reading from Value
Index access returns a Value; use accessor methods like as_str or as_i64 that return Option to read typed data safely.
use serde_json::Value;
fn name_of(v: &Value) -> Option<&str> {
v.get("name")?.as_str()
}Modeling JSON access in plain Rust
Reading a value by key, with a fallback when absent, mirrors how you query a Value object. Here it is with a HashMap.
use std::collections::HashMap;
fn main() {
let mut obj: HashMap<&str, &str> = HashMap::new();
obj.insert("name", "Alice");
let name = obj.get("name").copied().unwrap_or("unknown");
let city = obj.get("city").copied().unwrap_or("unknown");
println!("name={} city={}", name, city);
}Bytes and writers
For performance, to_vec serializes to bytes, and to_writer streams directly into any io::Write such as a file or socket.
use serde::Serialize;
#[derive(Serialize)]
struct Msg { text: String }
fn to_bytes(m: &Msg) -> Vec<u8> {
serde_json::to_vec(m).unwrap()
}Handling parse errors
from_str returns Result. Match on the error to give users a helpful message instead of panicking.
use serde::Deserialize;
#[derive(Deserialize)]
struct User { id: u32 }
fn parse(s: &str) -> String {
match serde_json::from_str::<User>(s) {
Ok(u) => format!("id {}", u.id),
Err(e) => format!("invalid JSON: {}", e),
}
}Converting between Value and structs
serde_json::from_value and to_value convert between a typed struct and the dynamic Value when you need both.
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct User { name: String }
fn main() {
let v = json!({"name": "Eve"});
let u: User = serde_json::from_value(v).unwrap();
println!("{}", u.name);
}Quick Check
Test your understanding of working with JSON.
Recap
You learned JSON handling with serde_json:
to_string/from_strconvert structs and JSON textto_string_prettyformats readably- The
json!macro andValuehandle dynamic JSON - Use accessors and
Resultto read and parse safely
Next: customizing serialization with field attributes.
Frequently asked questions
Is the “Working with JSON” lesson free?
Yes — the full text of “Working with JSON” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Working with JSON”?
serde_json. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Working with JSON” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Serialize and Deserialize
- Working with JSON
- Custom Serialization
- Other Formats