Handling JSON
Apply functional programming practices to define a library to handle JSON.
Functional programming is an excellent fit for processing hierarchical data structures, such as formal languages or data formats. In this lesson, we’ll use OCaml to represent and manipulate JSON—a text-based data exchange format widely used to exchange data across the network, such as in web services. Handling JSON provides us with an excellent opportunity to apply many of the techniques we’ve learned, including algebraic datatypes, functions, and higher-order functions.
The following example shows a possible JSON representation describing the classic movie “The Godfather.” For the sake of simplicity, we’ll list only three actors in this example:
{
"title": "Godfather",
"genre": [
"crime",
"drama"
],
"year": 1972,
"actors": [
{
"actor": "Marlon Brando",
"character": "Vito Corleone",
"is_major_character": true
},
{
"actor": "Al Pacino",
"character": "Michael Corleone",
"is_major_character": true
},
{
"actor": "Lenny Montana",
"character": "Luca Brasi",
"is_major_character": false
}
],
"is_on_netflix": true
}
A JSON structure like the one above may be used by a desktop application to store movie data. It might also come from a web service, like REST API, which provides movie information.
Get hands-on with 1400+ tech skills courses.