Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Strongly typed JSON library for Rust

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
NotificationsYou must be signed in to change notification settings

serde-rs/json

Repository files navigation

Serde is a framework forserializing anddeserializing Rust data structures efficiently and generically.


[dependencies]serde_json ="1.0"

You may be looking for:

JSON is a ubiquitous open-standard format that uses human-readable text totransmit data objects consisting of key-value pairs.

{"name":"John Doe","age":43,"address": {"street":"10 Downing Street","city":"London"    },"phones": ["+44 1234567","+44 2345678"    ]}

There are three common ways that you might find yourself needing to work withJSON data in Rust.

  • As text data. An unprocessed string of JSON data that you receive on anHTTP endpoint, read from a file, or prepare to send to a remote server.
  • As an untyped or loosely typed representation. Maybe you want to checkthat some JSON data is valid before passing it on, but without knowing thestructure of what it contains. Or you want to do very basic manipulationslike insert a key in a particular spot.
  • As a strongly typed Rust data structure. When you expect all or most ofyour data to conform to a particular structure and want to get real work donewithout JSON's loosey-goosey nature tripping you up.

Serde JSON provides efficient, flexible, safe ways of converting data betweeneach of these representations.

Operating on untyped JSON values

Any valid JSON data can be manipulated in the following recursive enumrepresentation. This data structure isserde_json::Value.

enumValue{Null,Bool(bool),Number(Number),String(String),Array(Vec<Value>),Object(Map<String,Value>),}

A string of JSON data can be parsed into aserde_json::Value by theserde_json::from_str function. There is alsofrom_slice for parsing from a byte slice&[u8] andfrom_reader for parsing from anyio::Read like a File or aTCP stream.

use serde_json::{Result,Value};fnuntyped_example() ->Result<()>{// Some JSON input data as a &str. Maybe this comes from the user.let data =r#"        {            "name": "John Doe",            "age": 43,            "phones": [                "+44 1234567",                "+44 2345678"            ]        }"#;// Parse the string of data into serde_json::Value.let v:Value = serde_json::from_str(data)?;// Access parts of the data by indexing with square brackets.println!("Please call {} at the number {}", v["name"], v["phones"][0]);Ok(())}

The result of square bracket indexing likev["name"] is a borrow of the dataat that index, so the type is&Value. A JSON map can be indexed with stringkeys, while a JSON array can be indexed with integer keys. If the type of thedata is not right for the type with which it is being indexed, or if a map doesnot contain the key being indexed, or if the index into a vector is out ofbounds, the returned element isValue::Null.

When aValue is printed, it is printed as a JSON string. So in the code above,the output looks likePlease call "John Doe" at the number "+44 1234567". Thequotation marks appear becausev["name"] is a&Value containing a JSONstring and its JSON representation is"John Doe". Printing as a plain stringwithout quotation marks involves converting from a JSON string to a Rust stringwithas_str() or avoiding the use ofValue as described in the followingsection.

TheValue representation is sufficient for very basic tasks but can be tediousto work with for anything more significant. Error handling is verbose toimplement correctly, for example imagine trying to detect the presence ofunrecognized fields in the input data. The compiler is powerless to help youwhen you make a mistake, for example imagine typoingv["name"] asv["nmae"]in one of the dozens of places it is used in your code.

Parsing JSON as strongly typed data structures

Serde provides a powerful way of mapping JSON data into Rust data structureslargely automatically.

use serde::{Deserialize,Serialize};use serde_json::Result;#[derive(Serialize,Deserialize)]structPerson{name:String,age:u8,phones:Vec<String>,}fntyped_example() ->Result<()>{// Some JSON input data as a &str. Maybe this comes from the user.let data =r#"        {            "name": "John Doe",            "age": 43,            "phones": [                "+44 1234567",                "+44 2345678"            ]        }"#;// Parse the string of data into a Person object. This is exactly the// same function as the one that produced serde_json::Value above, but// now we are asking it for a Person as output.let p:Person = serde_json::from_str(data)?;// Do things just like with any other Rust data structure.println!("Please call {} at the number {}", p.name, p.phones[0]);Ok(())}

This is the sameserde_json::from_str function as before, but this time weassign the return value to a variable of typePerson so Serde willautomatically interpret the input data as aPerson and produce informativeerror messages if the layout does not conform to what aPerson is expected tolook like.

Any type that implements Serde'sDeserialize trait can be deserialized thisway. This includes built-in Rust standard library types likeVec<T> andHashMap<K, V>, as well as any structs or enums annotated with#[derive(Deserialize)].

Once we havep of typePerson, our IDE and the Rust compiler can help us useit correctly like they do for any other Rust code. The IDE can autocompletefield names to prevent typos, which was impossible in theserde_json::Valuerepresentation. And the Rust compiler can check that when we writep.phones[0], thenp.phones is guaranteed to be aVec<String> so indexinginto it makes sense and produces aString.

The necessary setup for using Serde's derive macros is explained on theUsingderive page of the Serde site.

Constructing JSON values

Serde JSON provides ajson! macro to buildserde_json::Valueobjects with very natural JSON syntax.

use serde_json::json;fnmain(){// The type of `john` is `serde_json::Value`let john =json!({"name":"John Doe","age":43,"phones":["+44 1234567","+44 2345678"]});println!("first phone number: {}", john["phones"][0]);// Convert to a string of JSON and print it outprintln!("{}", john.to_string());}

TheValue::to_string() function converts aserde_json::Value into aStringof JSON text.

One neat thing about thejson! macro is that variables and expressions can beinterpolated directly into the JSON value as you are building it. Serde willcheck at compile time that the value you are interpolating is able to berepresented as JSON.

let full_name ="John Doe";let age_last_year =42;// The type of `john` is `serde_json::Value`let john =json!({"name": full_name,"age": age_last_year +1,"phones":[        format!("+44 {}", random_phone())]});

This is amazingly convenient, but we have the problem we had before withValue: the IDE and Rust compiler cannot help us if we get it wrong. Serde JSONprovides a better way of serializing strongly-typed data structures into JSONtext.

Creating JSON by serializing data structures

A data structure can be converted to a JSON string byserde_json::to_string. There is alsoserde_json::to_vec which serializes to aVec<u8> andserde_json::to_writer which serializes to anyio::Writesuch as a File or a TCP stream.

use serde::{Deserialize,Serialize};use serde_json::Result;#[derive(Serialize,Deserialize)]structAddress{street:String,city:String,}fnprint_an_address() ->Result<()>{// Some data structure.let address =Address{street:"10 Downing Street".to_owned(),city:"London".to_owned(),};// Serialize it to a JSON string.let j = serde_json::to_string(&address)?;// Print, write to a file, or send to an HTTP server.println!("{}", j);Ok(())}

Any type that implements Serde'sSerialize trait can be serialized this way.This includes built-in Rust standard library types likeVec<T> andHashMap<K, V>, as well as any structs or enums annotated with#[derive(Serialize)].

Performance

It is fast. You should expect in the ballpark of 500 to 1000 megabytes persecond deserialization and 600 to 900 megabytes per second serialization,depending on the characteristics of your data. This is competitive with thefastest C and C++ JSON libraries or even 30% faster for many use cases.Benchmarks live in theserde-rs/json-benchmark repo.

Getting help

Serde is one of the most widely used Rust libraries, so any place thatRustaceans congregate will be able to help you out. For chat, consider tryingthe#rust-questions or#rust-beginners channels of the unofficial communityDiscord (invite:https://discord.gg/rust-lang-community), the#rust-usage or#beginners channels of the official Rust Project Discord (invite:https://discord.gg/rust-lang), or the#general stream in Zulip. Forasynchronous, consider the[rust] tag on StackOverflow, the/r/rust subreddit which has a pinned weekly easy questions post, or the RustDiscourse forum. It's acceptable to file a support issue in thisrepo, but they tend not to get as many eyes as any of the above and may getclosed without a response after some time.

No-std support

As long as there is a memory allocator, it is possible to use serde_json withoutthe rest of the Rust standard library. Disable the default "std" feature andenable the "alloc" feature:

[dependencies]serde_json = {version ="1.0",default-features =false,features = ["alloc"] }

For JSON support in Serde without a memory allocator, please see theserde-json-core crate.


License

Licensed under either ofApache License, Version2.0 orMIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submittedfor inclusion in this crate by you, as defined in the Apache-2.0 license, shallbe dual licensed as above, without any additional terms or conditions.

[8]ページ先頭

©2009-2025 Movatter.jp