Updated June 12, 2023
Introduction to Rust JSON
JSON stands for Javascript Object Notation, it works in the same way like any other programming language. JSON are very light weight and store anything inside them, mainly JSON in rust or any other programming language is used to transfer data from server to web pages and vice versa. Inside the JSON in rust we can store anything like objects, array, etc. JSON have a specific format which we need to follow if we want to parse or deparse our object to Json otherwise, we will receive parsing expectation at runtime. JSON always starts with a ‘{‘curly braces and ends with a’}’ curly braces in rust or any other programming language. In the coming section of the tutorial, we will learn the internal working of the JSON and how to implement this in the program using rust.
Syntax
We know that while dealing with Json, we have to follow some standard defined by the JSON library. They have some specific format to define Json. Let’s have a look at the syntax to explain Json in rust for better understanding, see below;
let variable_name = json::parse(your_json obje).unwrap();
As you can see in the above lines of syntax, we are using json here , inside this, we are passing our object to give us the JSON object in return. But to make it work, we have to include the crate json dependency in our project. Let’s see one practice syntax for better understating. See below;
Example:
let demo = json::parse(r#"
{
"abc" : "123"
}
"#).unwrap();
You can follow the above steps to create the JSON in rust, in the coming section we will discuss more about the internal working and dependency require for this to work in detail for beginners.
How JSON works in Rust?
As we already discussed that JSON in rust is just like normal JSON in other programming language. It can store anything inside it in the form of key value pair. JSON can contain anything inside them, object, array, etc. Object can also be converted into JSON using libraries available. In this tutorial, we are using crate and serialization API to deal with the JSON in rust. In this tutorial, we will learn more about its working and implementation in detail see below;
To use json inside the program, we have to include the dependency, and after that, we can use this in the program only. Json have a specific format. also, inside JSON, we have objects and their values in the form of key and value pair. To create a json object, we have to use serialization dependency in Rust, in our program, we have to import it in the first place. else it will give us an error. Let’s take a look at the steps that we need to take while using JSON in rust see below;
1. In order to use json inside the code, we have to include the below-specified dependency into our code.
Example:
extern crate serialize;
use serialize::json;
At the program’s, start, we must include the abovementioned library. After this, we can use its method to create our json object in rust. In the coming section of the tutorial, we will see how to use them.
We also have one more library that can be used to deal with the json in Rust. We can have a look at this dependency also see below;
1. First, add the below dependency into the cargo. toml file. After this, only we can deal with json in rust. For more information, see below;
Example:
[dependencies]
serde = { version = "1", features = ["derive"] }
2. After this, we can use the below lines of code in any class in which we want the josn object. Below mentioning the lines of code which need to include in the class object see below;
Example:
use serde::{Deserialize, Serialize};
// mandatory lines to use json in rust
#[derive(Debug, Deserialize, Serialize)]
We are trying to use the above lines like any other macros in rust.
3. After this configuration, in the main() method, we can create the object of our class and pass it inside the json method available by the dependency of serde. In this section, we will provide one practice example for beginners to understand the requirement and implementation in detail see below;
Example:
1. First, we can create the struct in rust with the following configuration on it.
Example:
struct DemoObj {
name: String,
city: String,
add: String,
id: usize,
}
2. Code in the main method should be like this see below;
Example:
fn main() {
let myobj = r#"
{
"name": "Amit vyas",
"city": "Mumbai",
"add": "mumbai street",
"id" :001
}
"#;
let demo: DemoObj = serde_json::from_str(myobj).unwrap();
}
In the above lines of code, we first create the object for the struct that we created in the first step. To create the object, we have followed some standard already define. Inside this {} braces, we are trying to define the values for the variable that we have used in the struct. After that, we use serde API to convert the object into JSON. we have used unwrap() method for it. But be sure that we have to use serde dependency into the cargo. toml file otherwise, the example will not be work.
Examples
1. In this example, we are trying to use serde library to deal with json in rust, also, keep in mind that you need to setup the serde dependency in your configure file, then only the below mentioned example will work. otherwise, it will not, also it will not work using any only compiler for rust.
Example:
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
struct DemoObjectStruct {
rolno:usize,
name: String,
city: String,
salary : usize,
}
fn main() {
println!("demo to show json in rust !!");
println!("creating json object below ::");
let demoobj = r#"
{
"rolno": 001,
"name": "dummy name here",
"city": "mumbai",
"salary" : 1000
}
"#;
let jobject: DemoObjectStruct = serde_json::from_str(demoobj).unwrap();
println!("prinitng value og jsn objetc :: ");
println!("value inside the json objetc is :: {:?}", jobject);
}
Output:
Conclusion
JSON is very light weighted, and also they can store any object inside them. Mainly they are used to deal with request and response between server and web pages. We can made a JSON object by using any object, array, or list of object inside it, it supports everything and is very easy to handle.
Recommended Articles
We hope that this EDUCBA information on “Rust JSON” was beneficial to you. You can view EDUCBA’s recommended articles for more information.