Charles Cooper

Charles Cooper

1600695659

JSON and Rust: Why serde_json is The Top Choice

JSON support is very much production-ready and arguably best in class compared to other mainstream languages.

JSON has become one of the most common data exchange formats on the web, so it’s critical that server-side languages have good support for it. Fortunately, dealing with JSON is an area where Rust shines, thanks in large part to the serde and serde_json crates. These are among the most battle-tested crates in the Rust ecosystem and serve as great examples of ways to exploit Rust’s high-level abstractions while maintaining low-level control.

While there are plenty of other JSON crates available, serde_json is by far the most popular. The large ecosystem built around serde makes it the top choice for web servers written in Rust.

In this tutorial, we’ll explore serde_json and demonstrate how to use Rust’s type system to express JSON data.

Getting started

To get started with serde_json, you must first implement the Serialize and Deserialize traits on your types. Thanks to derive macros, this is really trivial for most types. To use derive macros, make sure you enable the “derive” feature flag for serde in your dependencies.

## cargo.toml

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Now we can use them like any other derive macro.

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct Person {
    name: String,
    age: usize,
    verified: bool,
}

That’s all you need to do to make Person serializable and deserializable into any data format with a crate that supports serde. Debug is optional, but we’ll use it for demonstration purposes. Converting a JSON string into an instance of Person is now as simple as calling serde_json::from_str.

fn main() {
    let json = r#"
        {
          "name": "George",
          "age": 27,
          "verified": false
        }
    "#;

    let person: Person = serde_json::from_str(json).unwrap();

    println!("{:?}", person);
}

There are a couple of things to point out here, the first being the explicit Person type annotation. In this example, there is no way for the compiler to infer the type of person; it could potentially be any type that implements Deserialize. In more complete examples it would be inferred from things like function argument types when passing around person.

The other thing to note is the call to unwrap(). Deserialization can fail in a number of ways, so serde_json::from_str returns a Result to let us handle those failures. Errors from serde_json are quite rich and give us enough information to pin down exactly what went wrong. For example, running the same code as above with the age field removed triggers the following error message.

Error("missing field `age`", line: 5, column: 9)

You would get a similar message if there were syntax errors in the JSON. Instead of using unwrap, you can extract the same information seen above by using the methods provided by serde_json::Error and handle the error gracefully whenever possible.

One of my favorite things about using JSON in Rust is that it provides complete type checking with zero boilerplate code and error handling that is enforced at compile time thanks to the Result type. The places where you use JSON are almost always at system boundaries where you can receive all kinds of unexpected inputs. Having first-class, consistent support for error handling makes dealing with these system boundaries much more enjoyable and reliable.

#rust #json #javascript #programming #developer

What is GEEK

Buddha Community

JSON and Rust: Why serde_json is The Top Choice
Awesome  Rust

Awesome Rust

1654894080

Serde JSON: JSON Support for Serde Framework

Serde JSON

Serde is a framework for serializing and deserializing 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 to transmit 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 with JSON data in Rust.

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

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

Operating on untyped JSON values

Any valid JSON data can be manipulated in the following recursive enum representation. This data structure is serde_json::Value.

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

A string of JSON data can be parsed into a serde_json::Value by the serde_json::from_str function. There is also from_slice for parsing from a byte slice &[u8] and from_reader for parsing from any io::Read like a File or a TCP stream.

use serde_json::{Result, Value};

fn untyped_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 like v["name"] is a borrow of the data at that index, so the type is &Value. A JSON map can be indexed with string keys, while a JSON array can be indexed with integer keys. If the type of the data is not right for the type with which it is being indexed, or if a map does not contain the key being indexed, or if the index into a vector is out of bounds, the returned element is Value::Null.

When a Value is printed, it is printed as a JSON string. So in the code above, the output looks like Please call "John Doe" at the number "+44 1234567". The quotation marks appear because v["name"] is a &Value containing a JSON string and its JSON representation is "John Doe". Printing as a plain string without quotation marks involves converting from a JSON string to a Rust string with as_str() or avoiding the use of Value as described in the following section.

The Value representation is sufficient for very basic tasks but can be tedious to work with for anything more significant. Error handling is verbose to implement correctly, for example imagine trying to detect the presence of unrecognized fields in the input data. The compiler is powerless to help you when you make a mistake, for example imagine typoing v["name"] as v["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 structures largely automatically.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

fn typed_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 same serde_json::from_str function as before, but this time we assign the return value to a variable of type Person so Serde will automatically interpret the input data as a Person and produce informative error messages if the layout does not conform to what a Person is expected to look like.

Any type that implements Serde's Deserialize trait can be deserialized this way. This includes built-in Rust standard library types like Vec<T> and HashMap<K, V>, as well as any structs or enums annotated with #[derive(Deserialize)].

Once we have p of type Person, our IDE and the Rust compiler can help us use it correctly like they do for any other Rust code. The IDE can autocomplete field names to prevent typos, which was impossible in the serde_json::Value representation. And the Rust compiler can check that when we write p.phones[0], then p.phones is guaranteed to be a Vec<String> so indexing into it makes sense and produces a String.

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

Constructing JSON values

Serde JSON provides a json! macro to build serde_json::Value objects with very natural JSON syntax.

use serde_json::json;

fn main() {
    // 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 out
    println!("{}", john.to_string());
}

The Value::to_string() function converts a serde_json::Value into a String of JSON text.

One neat thing about the json! macro is that variables and expressions can be interpolated directly into the JSON value as you are building it. Serde will check at compile time that the value you are interpolating is able to be represented 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 with Value: the IDE and Rust compiler cannot help us if we get it wrong. Serde JSON provides a better way of serializing strongly-typed data structures into JSON text.

Creating JSON by serializing data structures

A data structure can be converted to a JSON string by serde_json::to_string. There is also serde_json::to_vec which serializes to a Vec<u8> and serde_json::to_writer which serializes to any io::Write such as a File or a TCP stream.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Address {
    street: String,
    city: String,
}

fn print_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's Serialize trait can be serialized this way. This includes built-in Rust standard library types like Vec<T> and HashMap<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 per second deserialization and 600 to 900 megabytes per second serialization, depending on the characteristics of your data. This is competitive with the fastest C and C++ JSON libraries or even 30% faster for many use cases. Benchmarks live in the serde-rs/json-benchmark repo.

Getting help

Serde is one of the most widely used Rust libraries, so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (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. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo, but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

No-std support

As long as there is a memory allocator, it is possible to use serde_json without the rest of the Rust standard library. This is supported on Rust 1.36+. Disable the default "std" feature and enable 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 the serde-json-core crate.

Link: https://crates.io/crates/serde_json

#rust  #rustlang  #encode   #json 

Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Serde Rust: Serialization Framework for Rust

Serde

*Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.*

You may be looking for:

Serde in action

Click to show Cargo.toml. Run this code in the playground.

[dependencies]

# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }

# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"

 

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&point).unwrap();

    // Prints serialized = {"x":1,"y":2}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!("deserialized = {:?}", deserialized);
}

Getting help

Serde is one of the most widely used Rust libraries so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (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. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

Download Details:
Author: serde-rs
Source Code: https://github.com/serde-rs/serde
License: View license

#rust  #rustlang 

Charles Cooper

Charles Cooper

1600695659

JSON and Rust: Why serde_json is The Top Choice

JSON support is very much production-ready and arguably best in class compared to other mainstream languages.

JSON has become one of the most common data exchange formats on the web, so it’s critical that server-side languages have good support for it. Fortunately, dealing with JSON is an area where Rust shines, thanks in large part to the serde and serde_json crates. These are among the most battle-tested crates in the Rust ecosystem and serve as great examples of ways to exploit Rust’s high-level abstractions while maintaining low-level control.

While there are plenty of other JSON crates available, serde_json is by far the most popular. The large ecosystem built around serde makes it the top choice for web servers written in Rust.

In this tutorial, we’ll explore serde_json and demonstrate how to use Rust’s type system to express JSON data.

Getting started

To get started with serde_json, you must first implement the Serialize and Deserialize traits on your types. Thanks to derive macros, this is really trivial for most types. To use derive macros, make sure you enable the “derive” feature flag for serde in your dependencies.

## cargo.toml

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Now we can use them like any other derive macro.

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct Person {
    name: String,
    age: usize,
    verified: bool,
}

That’s all you need to do to make Person serializable and deserializable into any data format with a crate that supports serde. Debug is optional, but we’ll use it for demonstration purposes. Converting a JSON string into an instance of Person is now as simple as calling serde_json::from_str.

fn main() {
    let json = r#"
        {
          "name": "George",
          "age": 27,
          "verified": false
        }
    "#;

    let person: Person = serde_json::from_str(json).unwrap();

    println!("{:?}", person);
}

There are a couple of things to point out here, the first being the explicit Person type annotation. In this example, there is no way for the compiler to infer the type of person; it could potentially be any type that implements Deserialize. In more complete examples it would be inferred from things like function argument types when passing around person.

The other thing to note is the call to unwrap(). Deserialization can fail in a number of ways, so serde_json::from_str returns a Result to let us handle those failures. Errors from serde_json are quite rich and give us enough information to pin down exactly what went wrong. For example, running the same code as above with the age field removed triggers the following error message.

Error("missing field `age`", line: 5, column: 9)

You would get a similar message if there were syntax errors in the JSON. Instead of using unwrap, you can extract the same information seen above by using the methods provided by serde_json::Error and handle the error gracefully whenever possible.

One of my favorite things about using JSON in Rust is that it provides complete type checking with zero boilerplate code and error handling that is enforced at compile time thanks to the Result type. The places where you use JSON are almost always at system boundaries where you can receive all kinds of unexpected inputs. Having first-class, consistent support for error handling makes dealing with these system boundaries much more enjoyable and reliable.

#rust #json #javascript #programming #developer

Why serde_json is the top choice in JSON and Rust

JSON has become one of the most common data exchange formats on the web, so it’s critical that server-side languages have good support for it. Fortunately, dealing with JSON is an area where Rust shines, thanks in large part to the serde and serde_json crates. These are among the most battle-tested crates in the Rust ecosystem and serve as great examples of ways to exploit Rust’s high-level abstractions while maintaining low-level control.

While there are plenty of other JSON crates available, serde_json is by far the most popular. The large ecosystem built around serde makes it the top choice for web servers written in Rust.

In this tutorial, we’ll explore serde_json and demonstrate how to use Rust’s type system to express JSON data.

Getting started

To get started with serde_json, you must first implement the Serialize and Deserialize traits on your types. Thanks to derive macros, this is really trivial for most types. To use derive macros, make sure you enable the “derive” feature flag for serde in your dependencies.

# cargo.toml

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Now we can use them like any other derive macro.

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct Person {
    name: String,
    age: usize,
    verified: bool,
}

That’s all you need to do to make Person serializable and deserializable into any data format with a crate that supports serde. Debug is optional, but we’ll use it for demonstration purposes. Converting a JSON string into an instance of Person is now as simple as calling serde_json::from_str.

fn main() {
    let json = r#"
        {
          "name": "George",
          "age": 27,
          "verified": false
        }
    "#;

    let person: Person = serde_json::from_str(json).unwrap();

    println!("{:?}", person);
}

There are a couple of things to point out here, the first being the explicit Person type annotation. In this example, there is no way for the compiler to infer the type of person; it could potentially be any type that implements Deserialize. In more complete examples it would be inferred from things like function argument types when passing around person.

The other thing to note is the call to unwrap(). Deserialization can fail in a number of ways, so serde_json::from_str returns a Result to let us handle those failures. Errors from serde_json are quite rich and give us enough information to pin down exactly what went wrong. For example, running the same code as above with the age field removed triggers the following error message.

Error("missing field `age`", line: 5, column: 9)

You would get a similar message if there were syntax errors in the JSON. Instead of using unwrap, you can extract the same information seen above by using the methods provided by serde_json::Error and handle the error gracefully whenever possible.

One of my favorite things about using JSON in Rust is that it provides complete type checking with zero boilerplate code and error handling that is enforced at compile time thanks to the Result type. The places where you use JSON are almost always at system boundaries where you can receive all kinds of unexpected inputs. Having first-class, consistent support for error handling makes dealing with these system boundaries much more enjoyable and reliable.

Server example

So far, we’ve only scratched the surface of what serde and serde_json can do. To show them in action, we’ll create a server that calculates the perimeter and area of various shapes. We want requests to send JSON that look something like this:

{
  "calculation": "area",
  "shape": "circle",
  "radius": 4.5
}

As is often a good idea in Rust, we’ll start by thinking about types. The value of the calculation field in JSON is just a string. While we could use a Rust String, we need to enforce some invariants that aren’t captured by the String type. Instead of allowing any string value, we really just want to allow perimeter or area. A natural fit for something like this is an enum.

#[derive(Debug, Deserialize, Serialize)]
enum Calculation {
    Perimeter,
    Area,
}

JSON doesn’t include the concept of enums, but that’s OK because serde is flexible enough to massage these data types into a JSON equivalent. By default, the variants of Calculation will be converted to the JSON strings Perimeter and Area. That’s fine, but we’d prefer it if the strings were all lowercase. To accomplish that, we need to use our first serde attribute macro.

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
enum Calculation {
    Perimeter,
    Area,
}

As the name suggests, rename_all = "lowercase" will map the enum variants to lowercase strings in JSON.

The next fields in our desired JSON format are the shape name and the properties of that shape. These fields are tightly coupled to one another. A circle should have a radius, but a rectangle should not. To enforce this coupling in our types, we can use an enum with associated data.

#[derive(Debug, Deserialize, Serialize)]
enum Shape {
    Circle {
        radius: f64,
    },
    Rectangle {
        length: f64,
        width: f64,
    },
}

By default, this is represented by an externally tagged JSON object and adds nesting that we don’t want.

{
  "Circle": {
    "radius": 4.5
  }
}

We can fix this with another attribute.

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase", tag = "shape")]
enum Shape {
    Circle {
        radius: f64,
    },
    Rectangle {
        length: f64,
        width: f64,
    },
}

The tag = "shape" attribute causes the JSON object to be internally tagged with a key of shape, giving the following.

{
  "shape": "circle",
  "radius": 4.5
}

Now we can create a Request type that puts a Calculation and a Shape together.

#[derive(Debug, Deserialize, Serialize)]
struct Request {
    calculation: Calculation,
    shape: Shape,
}

As you might have noticed, this type adds another layer of nesting that doesn’t match our desired JSON format.

{
  "calculation": "area",
  "shape": {
    "shape": "circle",
    "radius": 4.5
  }
}

Once again, we can solve this with an attribute.

#[derive(Debug, Deserialize, Serialize)]
struct Request {
    calculation: Calculation,
    #[serde(flatten)]
    shape: Shape,
}

This time, the flatten attribute is used to remove a layer of nesting. This can also often be useful in situations where you have a JSON object that contains some keys that don’t have a predictable name. To solve this, you can create a type where the known fields are mapped directly to a struct field and the unknown ones can be collected in a flattened HashMap.

You can now test what we have done so far in the same way we tested the Person type before.

fn main() {
    let json = r#"
        {
          "calculation": "perimeter",
          "shape": "circle",
          "radius": 2.3
        }
    "#;

    let request: Request = serde_json::from_str(json).unwrap();

    println!("{:?}", request);
}

I encourage you to play around with the input JSON to see how robust the type validation is and how helpful the errors are.

The final type we need for our application is a Response, which contains the result of the calculation.

#[derive(Debug, Deserialize, Serialize)]
struct Response {
    result: f64,
}

With all the types in place, we can build the logic that will actually perform the calculations.

use std::f64::consts::PI;

fn calculation_handler(request: Request) -> Response {
    let result = match (request.calculation, request.shape) {
        (Calculation::Perimeter, Shape::Circle { radius }) => PI * 2.0 * radius,
        (Calculation::Perimeter, Shape::Rectangle { length, width }) => 2.0 * length + 2.0 * width,
        (Calculation::Area, Shape::Circle { radius }) => PI * radius * radius,
        (Calculation::Area, Shape::Rectangle { length, width }) => length * width,
    };

    Response { result }
}

Since we’re enforcing invariants in the type system, our logic becomes simple and easy to reason about. In this case, it is a pure function that takes a Request and returns a Response, making it testable and completely decoupled from any web framework. One nice thing about serde is that it doesn’t force you to couple your logic and types to it since the derive macros don’t modify existing things; they purely add trait implementations.

As I mentioned earlier, serde_json can take advantage of the ecosystem around serde. Lots of crates contain code that is generic over types that implement the Serialize or Deserialize traits. A good example of this is web frameworks. Our handler already has a type signature that resembles a HTTP request-response cycle, so we will be able to plug it into any web framework that integrates with serde.

To build the web server, we need to add a couple of new dependencies.

[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "0.2", features = ["macros"] }
warp = "0.2"

Next, replace the main function with an async function that sets up and starts the server.

use warp::Filter;

#[tokio::main]
async fn main() {
    let endpoint = warp::post()
        .and(warp::body::json())
        .map(|body| warp::reply::json(&calculation_handler(body)));
    warp::serve(endpoint).run(([127, 0, 0, 1], 5000)).await;
}

Don’t worry too much about what’s going on here; the important part is the closure inside of map. All we need to do for our logic to work with the warp web server is wrap the response in warp::reply::json. warp can do this by using serde_json under the hood.

At this point, we can try sending POST requests with a JSON body to localhost:5000 to test whether everything, including error messages, now works over our HTTP API.

Now you should have a decent grasp on how you can use Rust types to deal with JSON. One key takeaway from this example is that you can use Rust types that don’t have the exact structure of the JSON you interact with. When using more advanced features of Rust’s type system that more naturally fit the problem than a simple key-value object, we are free to use them without worrying about additional boilerplate.

The full code for this example is on GitHub.

Working without types

Although it is usually best to use your own types and derive the Serialize and Deserialize traits with serde_json, sometimes you either can’t or don’t want to. For those cases, you can work directly with the serde_json Value type. This is an enum that contains a variant for each possible data type in JSON.

// serde_json::Value

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

An easy way create Values is with the serde_json::json macro. This essentially allows you to write JSON directly in Rust source code. If you have a Value representing an object or array, you can access the fields using Value::get, similar to Vec::get and HashMap::get.

use serde_json::json;

fn main() {
    let value = json!({
        "name": "Bob",
        "age": 51,
        "address": {
            "country": "Germany",
            "city": "Example City",
            "street": "Example Street"
        },
        "siblings": ["Alice", "Joe"]
    });

    println!(
        "{:?}",
        value.get("address").and_then(|name| name.get("country"))
    );
}

This example will print Some(String("Germany")). As you would expect, get returns an Option since the index or key might not exist.

That’s all there really is to using serde_json without custom types. As you might imagine this is useful for handling JSON with unknown keys and for quick prototypes. Since things like web frameworks are generic over the Serialize and Deserialize traits, which serde_json::Value implements, you can use these Values without any additional friction.

Conclusion

Being some of Rust’s most mature crates, serde and serde_json make working with JSON a breeze. In this guide, we went over how to use your own data types to represent known JSON structure and how to handle unknown JSON structures. Serde’s data model is extremely flexible, so you should be able to handle any JSON data with ergonomic, minimal boilerplate Rust.

To put it simply, JSON support shouldn’t be a concern for any Rust developer. It’s very much production-ready and arguably best in class compared to other mainstream languages. 

Source: https://blog.logrocket.com/json-and-rust-why-serde_json-is-the-top-choice/

#json #rust