One of the most impressive libraries with Rust is ‘serde’ and their respective libraries. There are a lot of cases where you want to convert serde_json other serde_X formats and back.

In this example, we convert a serde_json::Value to a serde_cbor::Value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use serde_json;
use serde_cbor;
use std::io;

fn main() {
let input = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;

let json: serde_json::Value = serde_json::from_str(input).unwrap();
let cbor: serde_cbor::Value = serde_cbor::to_value(&json).unwrap();
println!("{:?}", cbor);
}