Better Programming

Advice for programmers.

Member-only story

How to Work With JSON in Rust

4 min readJul 12, 2022

--

Photo by Shahadat Rahman on Unsplash

JSON is widely used nowadays, and even if Rust may not be the most used language for tools and apps that use JSON for their data, it is important to know how to treat this format in such a fast-growing language like Rust.

In this small article, you will learn to:

  • Read untyped JSON.
  • Read JSON as a strongly typed data structure.
  • Write JSON strings.

All using just the serde and serde-json Rust dependencies.

Untyped JSON

Rust is a strongly typed language, and JSON is a data format that does not specify the types of its values (on its own). If we don’t want or care about receiving JSON data that has a precise structure and typing, reading JSON as a recursive Enum is provided as a data structure by the serde_json library. This structure accepts bools, strings, numbers, arrays, and objects (and null values), so any valid JSON is accepted.

Let’s see how it works after setting up our cargo project ( cargo new handle_json) by adding the needed deps:

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

--

--

Tommaso De Ponti
Tommaso De Ponti

Written by Tommaso De Ponti

Building stuff, #Stellar. https://tdep.xycloo.com. Check my personal blog at https://heytdep.github.io for more specific and/or advanced articles.