DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at elbruno.com on

#Rust πŸ¦€ – Serializing and Deserializing data structures to JSON with Serde

Hi !

While I was creating a sample on how to use OpenAI APIs in Rust, I relized that I needed to serialize and deserialize some data in JSON format. Lucky me, Serde JSON works great !

Serde JSON

Serde JSON is a library for serializing and deserializing Rust data structures efficiently and generically12. It provides ways to convert between different representations of JSON data, such as:

  • 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 up3.
  • As an untyped JSON value. When you want to work with data that does not have a predefined structure3.
  • As a stream of JSON events. When you need to read or write large messages with minimal memory overhead3.

Tool to convert JSON to Rust Structs

My next step was to analyze one of the json response samples from OpenAI APIs, and manually create the data struct. I’m lazy, so I search and find this amazing website: https://transform.tools/json-to-rust-serde

2 seconds later, I have my structs to work with OpenAI APIs !

Next week I’ll share more details about the repo with samples on how to use OpenAI APIs in Rust.

Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.


Top comments (0)