Legend:
Library
Module
Module type
Parameter
Class
Class type
This module provides combinators for extracting fields from JSON values.
This module provides combinators for extracting fields from JSON values. This approach is recommended for reading a few fields from data returned by public APIs. However for more complex applications we recommend Atdgen.
In order to extract the "id" field, assuming it is mandatory, we would use the following OCaml code that operates on single JSON nodes:
open Yojson.Basic.Util
...
let id = json |> member "id" |> to_string in
...
In order to extract all the "title" fields, we would write the following OCaml code that operates on lists of JSON nodes, skipping undefined nodes and nodes of unexpected type:
open Yojson.Basic.Util
let extract_titles (json : Yojson.Basic.t) : string list =
[json]
|> filter_member "pages"
|> flatten
|> filter_member "title"
|> filter_string
Raised when the equivalent JavaScript operation on the JSON value would return undefined. Currently this only happens when an array index is out of bounds.
The conversion functions above cannot be used with map, because they do not return JSON values. This convenience function convert_each to_f arr is equivalent to List.map to_f (to_list arr).
The following functions operate on lists of JSON nodes. None of them raises an exception when a certain kind of node is expected but no node or the wrong kind of node is found. Instead of raising an exception, nodes that are not as expected are simply ignored.
val filter_map : ('a->'b option)->'a list->'b list
filter_map f l maps each element of the list l to an optional value using function f and unwraps the resulting values.