Deserialise JSON Data using ppx_yojson_conv

Task

Data Formats / JSON / Deserialise JSON Data

Opam Packages Used

  • ppx_yojson_conv Tested with version: v0.17.0 — Used libraries: ppx_yojson_conv
  • yojson Tested with version: 2.1.2 — Used libraries: yojson

Code

We open Ppx_yojson_conv_lib.Yojson_conv.Primitives to bring the functions that deserialise primitive types in scope.

open Ppx_yojson_conv_lib.Yojson_conv.Primitives

let json = {|
{
  "name": "ocaml",
  "url": "https://ocaml.org/"
}
|}

The annotation [@@deriving of_yojson] causes the PPX from ppx_yojson_conv to generate a function language_of_yojson that converts values from type Yojson.Safe.t to language.

type language = { 
  name: string; 
  url: string 
} [@@deriving of_yojson]

First we convert the JSON string to Yojson.Safe.t and then we use the generated function to create the record. If parsing fails, an Of_yojson_error exception is thrown that we can handle.

try
  let result = 
    json
    |> Yojson.Safe.from_string 
    |> language_of_yojson 
  Some result
with Ppx_yojson_conv_lib.Yojson_conv.Of_yojson_error (exception, _) ->
  let _ = 
    Printexc.to_string exception print_endline in
  None

Recipe not working? Comments not clear or out of date?

Open an issue or contribute to this recipe!