{"id":13439307,"url":"https://github.com/serde-rs/json","last_synced_at":"2025-05-13T10:53:43.384Z","repository":{"id":32319308,"uuid":"35894511","full_name":"serde-rs/json","owner":"serde-rs","description":"Strongly typed JSON library for Rust","archived":false,"fork":false,"pushed_at":"2025-03-16T07:03:58.000Z","size":3017,"stargazers_count":5173,"open_issues_count":193,"forks_count":580,"subscribers_count":38,"default_branch":"master","last_synced_at":"2025-05-13T00:01:56.208Z","etag":null,"topics":["json","rust","serde"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/serde-rs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-05-19T16:30:20.000Z","updated_at":"2025-05-12T18:40:04.000Z","dependencies_parsed_at":"2024-02-10T03:29:13.335Z","dependency_job_id":"ed434a8d-4074-447f-a972-6619417343dd","html_url":"https://github.com/serde-rs/json","commit_stats":{"total_commits":1409,"total_committers":131,"mean_commits":"10.755725190839694","dds":0.2264017033356991,"last_synced_commit":"9802c08d4ef1662cbbf92fabf7d6f4dc6aecfe9e"},"previous_names":[],"tags_count":178,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serde-rs%2Fjson","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serde-rs%2Fjson/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serde-rs%2Fjson/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serde-rs%2Fjson/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/serde-rs","download_url":"https://codeload.github.com/serde-rs/json/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253929307,"owners_count":21985799,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json","rust","serde"],"created_at":"2024-07-31T03:01:12.818Z","updated_at":"2025-05-13T10:53:43.354Z","avatar_url":"https://github.com/serde-rs.png","language":"Rust","readme":"# Serde JSON \u0026emsp; [![Build Status]][actions] [![Latest Version]][crates.io] [![Rustc Version 1.36+]][rustc]\n\n[Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/json/ci.yml?branch=master\n[actions]: https://github.com/serde-rs/json/actions?query=branch%3Amaster\n[Latest Version]: https://img.shields.io/crates/v/serde_json.svg\n[crates.io]: https://crates.io/crates/serde\\_json\n[Rustc Version 1.36+]: https://img.shields.io/badge/rustc-1.36+-lightgray.svg\n[rustc]: https://blog.rust-lang.org/2019/07/04/Rust-1.36.0.html\n\n**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**\n\n---\n\n```toml\n[dependencies]\nserde_json = \"1.0\"\n```\n\nYou may be looking for:\n\n- [JSON API documentation](https://docs.rs/serde_json)\n- [Serde API documentation](https://docs.rs/serde)\n- [Detailed documentation about Serde](https://serde.rs/)\n- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html)\n- [Release notes](https://github.com/serde-rs/json/releases)\n\nJSON is a ubiquitous open-standard format that uses human-readable text to\ntransmit data objects consisting of key-value pairs.\n\n```json\n{\n    \"name\": \"John Doe\",\n    \"age\": 43,\n    \"address\": {\n        \"street\": \"10 Downing Street\",\n        \"city\": \"London\"\n    },\n    \"phones\": [\n        \"+44 1234567\",\n        \"+44 2345678\"\n    ]\n}\n```\n\nThere are three common ways that you might find yourself needing to work with\nJSON data in Rust.\n\n - **As text data.** An unprocessed string of JSON data that you receive on an\n   HTTP endpoint, read from a file, or prepare to send to a remote server.\n - **As an untyped or loosely typed representation.** Maybe you want to check\n   that some JSON data is valid before passing it on, but without knowing the\n   structure of what it contains. Or you want to do very basic manipulations\n   like insert a key in a particular spot.\n - **As a strongly typed Rust data structure.** When you expect all or most of\n   your data to conform to a particular structure and want to get real work done\n   without JSON's loosey-goosey nature tripping you up.\n\nSerde JSON provides efficient, flexible, safe ways of converting data between\neach of these representations.\n\n## Operating on untyped JSON values\n\nAny valid JSON data can be manipulated in the following recursive enum\nrepresentation. This data structure is [`serde_json::Value`][value].\n\n```rust\nenum Value {\n    Null,\n    Bool(bool),\n    Number(Number),\n    String(String),\n    Array(Vec\u003cValue\u003e),\n    Object(Map\u003cString, Value\u003e),\n}\n```\n\nA string of JSON data can be parsed into a `serde_json::Value` by the\n[`serde_json::from_str`][from_str] function. There is also\n[`from_slice`][from_slice] for parsing from a byte slice `\u0026[u8]` and\n[`from_reader`][from_reader] for parsing from any `io::Read` like a File or a\nTCP stream.\n\n\u003cdiv align=\"right\"\u003e\n\u003ca href=\"https://play.rust-lang.org/?edition=2018\u0026gist=d69d8e3156d4bb81c4461b60b772ab72\" target=\"_blank\"\u003e\n\u003cimg align=\"center\" width=\"85\" src=\"https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png\"\u003e\n\u003c/a\u003e\n\u003c/div\u003e\n\n```rust\nuse serde_json::{Result, Value};\n\nfn untyped_example() -\u003e Result\u003c()\u003e {\n    // Some JSON input data as a \u0026str. Maybe this comes from the user.\n    let data = r#\"\n        {\n            \"name\": \"John Doe\",\n            \"age\": 43,\n            \"phones\": [\n                \"+44 1234567\",\n                \"+44 2345678\"\n            ]\n        }\"#;\n\n    // Parse the string of data into serde_json::Value.\n    let v: Value = serde_json::from_str(data)?;\n\n    // Access parts of the data by indexing with square brackets.\n    println!(\"Please call {} at the number {}\", v[\"name\"], v[\"phones\"][0]);\n\n    Ok(())\n}\n```\n\nThe result of square bracket indexing like `v[\"name\"]` is a borrow of the data\nat that index, so the type is `\u0026Value`. A JSON map can be indexed with string\nkeys, while a JSON array can be indexed with integer keys. If the type of the\ndata is not right for the type with which it is being indexed, or if a map does\nnot contain the key being indexed, or if the index into a vector is out of\nbounds, the returned element is `Value::Null`.\n\nWhen a `Value` is printed, it is printed as a JSON string. So in the code above,\nthe output looks like `Please call \"John Doe\" at the number \"+44 1234567\"`. The\nquotation marks appear because `v[\"name\"]` is a `\u0026Value` containing a JSON\nstring and its JSON representation is `\"John Doe\"`. Printing as a plain string\nwithout quotation marks involves converting from a JSON string to a Rust string\nwith [`as_str()`] or avoiding the use of `Value` as described in the following\nsection.\n\n[`as_str()`]: https://docs.rs/serde_json/1/serde_json/enum.Value.html#method.as_str\n\nThe `Value` representation is sufficient for very basic tasks but can be tedious\nto work with for anything more significant. Error handling is verbose to\nimplement correctly, for example imagine trying to detect the presence of\nunrecognized fields in the input data. The compiler is powerless to help you\nwhen you make a mistake, for example imagine typoing `v[\"name\"]` as `v[\"nmae\"]`\nin one of the dozens of places it is used in your code.\n\n## Parsing JSON as strongly typed data structures\n\nSerde provides a powerful way of mapping JSON data into Rust data structures\nlargely automatically.\n\n\u003cdiv align=\"right\"\u003e\n\u003ca href=\"https://play.rust-lang.org/?edition=2018\u0026gist=15cfab66d38ff8a15a9cf1d8d897ac68\" target=\"_blank\"\u003e\n\u003cimg align=\"center\" width=\"85\" src=\"https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png\"\u003e\n\u003c/a\u003e\n\u003c/div\u003e\n\n```rust\nuse serde::{Deserialize, Serialize};\nuse serde_json::Result;\n\n#[derive(Serialize, Deserialize)]\nstruct Person {\n    name: String,\n    age: u8,\n    phones: Vec\u003cString\u003e,\n}\n\nfn typed_example() -\u003e Result\u003c()\u003e {\n    // Some JSON input data as a \u0026str. Maybe this comes from the user.\n    let data = r#\"\n        {\n            \"name\": \"John Doe\",\n            \"age\": 43,\n            \"phones\": [\n                \"+44 1234567\",\n                \"+44 2345678\"\n            ]\n        }\"#;\n\n    // Parse the string of data into a Person object. This is exactly the\n    // same function as the one that produced serde_json::Value above, but\n    // now we are asking it for a Person as output.\n    let p: Person = serde_json::from_str(data)?;\n\n    // Do things just like with any other Rust data structure.\n    println!(\"Please call {} at the number {}\", p.name, p.phones[0]);\n\n    Ok(())\n}\n```\n\nThis is the same `serde_json::from_str` function as before, but this time we\nassign the return value to a variable of type `Person` so Serde will\nautomatically interpret the input data as a `Person` and produce informative\nerror messages if the layout does not conform to what a `Person` is expected to\nlook like.\n\nAny type that implements Serde's `Deserialize` trait can be deserialized this\nway. This includes built-in Rust standard library types like `Vec\u003cT\u003e` and\n`HashMap\u003cK, V\u003e`, as well as any structs or enums annotated with\n`#[derive(Deserialize)]`.\n\nOnce we have `p` of type `Person`, our IDE and the Rust compiler can help us use\nit correctly like they do for any other Rust code. The IDE can autocomplete\nfield names to prevent typos, which was impossible in the `serde_json::Value`\nrepresentation. And the Rust compiler can check that when we write\n`p.phones[0]`, then `p.phones` is guaranteed to be a `Vec\u003cString\u003e` so indexing\ninto it makes sense and produces a `String`.\n\nThe necessary setup for using Serde's derive macros is explained on the *[Using\nderive]* page of the Serde site.\n\n[Using derive]: https://serde.rs/derive.html\n\n## Constructing JSON values\n\nSerde JSON provides a [`json!` macro][macro] to build `serde_json::Value`\nobjects with very natural JSON syntax.\n\n\u003cdiv align=\"right\"\u003e\n\u003ca href=\"https://play.rust-lang.org/?edition=2018\u0026gist=6ccafad431d72b62e77cc34c8e879b24\" target=\"_blank\"\u003e\n\u003cimg align=\"center\" width=\"85\" src=\"https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png\"\u003e\n\u003c/a\u003e\n\u003c/div\u003e\n\n```rust\nuse serde_json::json;\n\nfn main() {\n    // The type of `john` is `serde_json::Value`\n    let john = json!({\n        \"name\": \"John Doe\",\n        \"age\": 43,\n        \"phones\": [\n            \"+44 1234567\",\n            \"+44 2345678\"\n        ]\n    });\n\n    println!(\"first phone number: {}\", john[\"phones\"][0]);\n\n    // Convert to a string of JSON and print it out\n    println!(\"{}\", john.to_string());\n}\n```\n\nThe `Value::to_string()` function converts a `serde_json::Value` into a `String`\nof JSON text.\n\nOne neat thing about the `json!` macro is that variables and expressions can be\ninterpolated directly into the JSON value as you are building it. Serde will\ncheck at compile time that the value you are interpolating is able to be\nrepresented as JSON.\n\n\u003cdiv align=\"right\"\u003e\n\u003ca href=\"https://play.rust-lang.org/?edition=2018\u0026gist=f9101a6e61dfc9e02c6a67f315ed24f2\" target=\"_blank\"\u003e\n\u003cimg align=\"center\" width=\"85\" src=\"https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png\"\u003e\n\u003c/a\u003e\n\u003c/div\u003e\n\n```rust\nlet full_name = \"John Doe\";\nlet age_last_year = 42;\n\n// The type of `john` is `serde_json::Value`\nlet john = json!({\n    \"name\": full_name,\n    \"age\": age_last_year + 1,\n    \"phones\": [\n        format!(\"+44 {}\", random_phone())\n    ]\n});\n```\n\nThis is amazingly convenient, but we have the problem we had before with\n`Value`: the IDE and Rust compiler cannot help us if we get it wrong. Serde JSON\nprovides a better way of serializing strongly-typed data structures into JSON\ntext.\n\n## Creating JSON by serializing data structures\n\nA data structure can be converted to a JSON string by\n[`serde_json::to_string`][to_string]. There is also\n[`serde_json::to_vec`][to_vec] which serializes to a `Vec\u003cu8\u003e` and\n[`serde_json::to_writer`][to_writer] which serializes to any `io::Write`\nsuch as a File or a TCP stream.\n\n\u003cdiv align=\"right\"\u003e\n\u003ca href=\"https://play.rust-lang.org/?edition=2018\u0026gist=3472242a08ed2ff88a944f2a2283b0ee\" target=\"_blank\"\u003e\n\u003cimg align=\"center\" width=\"85\" src=\"https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png\"\u003e\n\u003c/a\u003e\n\u003c/div\u003e\n\n```rust\nuse serde::{Deserialize, Serialize};\nuse serde_json::Result;\n\n#[derive(Serialize, Deserialize)]\nstruct Address {\n    street: String,\n    city: String,\n}\n\nfn print_an_address() -\u003e Result\u003c()\u003e {\n    // Some data structure.\n    let address = Address {\n        street: \"10 Downing Street\".to_owned(),\n        city: \"London\".to_owned(),\n    };\n\n    // Serialize it to a JSON string.\n    let j = serde_json::to_string(\u0026address)?;\n\n    // Print, write to a file, or send to an HTTP server.\n    println!(\"{}\", j);\n\n    Ok(())\n}\n```\n\nAny type that implements Serde's `Serialize` trait can be serialized this way.\nThis includes built-in Rust standard library types like `Vec\u003cT\u003e` and `HashMap\u003cK,\nV\u003e`, as well as any structs or enums annotated with `#[derive(Serialize)]`.\n\n## Performance\n\nIt is fast. You should expect in the ballpark of 500 to 1000 megabytes per\nsecond deserialization and 600 to 900 megabytes per second serialization,\ndepending on the characteristics of your data. This is competitive with the\nfastest C and C++ JSON libraries or even 30% faster for many use cases.\nBenchmarks live in the [serde-rs/json-benchmark] repo.\n\n[serde-rs/json-benchmark]: https://github.com/serde-rs/json-benchmark\n\n## Getting help\n\nSerde is one of the most widely used Rust libraries, so any place that\nRustaceans congregate will be able to help you out. For chat, consider trying\nthe [#rust-questions] or [#rust-beginners] channels of the unofficial community\nDiscord (invite: \u003chttps://discord.gg/rust-lang-community\u003e), the [#rust-usage] or\n[#beginners] channels of the official Rust Project Discord (invite:\n\u003chttps://discord.gg/rust-lang\u003e), or the [#general][zulip] stream in Zulip. For\nasynchronous, consider the [\\[rust\\] tag on StackOverflow][stackoverflow], the\n[/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust\n[Discourse forum][discourse]. It's acceptable to file a support issue in this\nrepo, but they tend not to get as many eyes as any of the above and may get\nclosed without a response after some time.\n\n[#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513\n[#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281\n[#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848\n[#beginners]: https://discord.com/channels/442252698964721669/448238009733742612\n[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general\n[stackoverflow]: https://stackoverflow.com/questions/tagged/rust\n[/r/rust]: https://www.reddit.com/r/rust\n[discourse]: https://users.rust-lang.org\n\n## No-std support\n\nAs long as there is a memory allocator, it is possible to use serde_json without\nthe rest of the Rust standard library. Disable the default \"std\" feature and\nenable the \"alloc\" feature:\n\n```toml\n[dependencies]\nserde_json = { version = \"1.0\", default-features = false, features = [\"alloc\"] }\n```\n\nFor JSON support in Serde without a memory allocator, please see the\n[`serde-json-core`] crate.\n\n[`serde-json-core`]: https://github.com/rust-embedded-community/serde-json-core\n\n[value]: https://docs.rs/serde_json/1/serde_json/value/enum.Value.html\n[from_str]: https://docs.rs/serde_json/1/serde_json/de/fn.from_str.html\n[from_slice]: https://docs.rs/serde_json/1/serde_json/de/fn.from_slice.html\n[from_reader]: https://docs.rs/serde_json/1/serde_json/de/fn.from_reader.html\n[to_string]: https://docs.rs/serde_json/1/serde_json/ser/fn.to_string.html\n[to_vec]: https://docs.rs/serde_json/1/serde_json/ser/fn.to_vec.html\n[to_writer]: https://docs.rs/serde_json/1/serde_json/ser/fn.to_writer.html\n[macro]: https://docs.rs/serde_json/1/serde_json/macro.json.html\n\n\u003cbr\u003e\n\n#### License\n\n\u003csup\u003e\nLicensed under either of \u003ca href=\"LICENSE-APACHE\"\u003eApache License, Version\n2.0\u003c/a\u003e or \u003ca href=\"LICENSE-MIT\"\u003eMIT license\u003c/a\u003e at your option.\n\u003c/sup\u003e\n\n\u003cbr\u003e\n\n\u003csub\u003e\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in this crate by you, as defined in the Apache-2.0 license, shall\nbe dual licensed as above, without any additional terms or conditions.\n\u003c/sub\u003e\n","funding_links":[],"categories":["Libraries","Rust","库 Libraries","tools","库","Rust 程序设计","Libraries by Language","File Processing","虚拟化"],"sub_categories":["Encoding","编码 Encoding","编码(Encoding)","加密 Encoding","网络服务_其他","Rust","编码"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fserde-rs%2Fjson","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fserde-rs%2Fjson","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fserde-rs%2Fjson/lists"}