e.g.:
utop # Format.printf "%a@." (Yojson.Basic.pretty_print ~std:true) (`Int 5);;
Exception:
Yojson.Json_error
"Root is not an object or array as requested by the JSON standard"
My first question is, where does the standard request that JSON values aside from objects and arrays not be printed? Looking at json.org, and the actual ECMA standard, I don't see any language to this effect. On the contrary, the ECMA document states plainly that "A JSON value can be an object, array, number, string, true, false, or null", and the quasi-BNF on the side of json.org is pretty clear that any of these things is a valid JSON value.
Beyond litigating the specification though, the current behaviour is just incredibly unhelpful. Javascript runtimes happily parse and stringify non-object and non-array "root" values, and OCaml programs need to deal with the same. To that end, I consistently carry around these functions so I can serialize JSON values as required by APIs and other programs (with the understanding my half-measure treatment of printing these atoms might actually be slightly off):
let pp_json f fmt =
let open Format in
function
| `Null -> pp_print_string fmt "null"
| `Int v -> pp_print_int fmt v
| `Float v -> pp_print_float fmt v
| `String v -> fprintf fmt "%S" v
| `Bool v -> pp_print_bool fmt v
| v -> fprintf fmt "@[%a@]" f v
let pp_json_basic = pp_json (Yojson.Basic.pretty_print ~std:true)
let pp_json_safe = pp_json (Yojson.Safe.pretty_print ~std:true)
Can we remove this limitation?
e.g.:
My first question is, where does the standard request that JSON values aside from objects and arrays not be printed? Looking at json.org, and the actual ECMA standard, I don't see any language to this effect. On the contrary, the ECMA document states plainly that "A JSON value can be an object, array, number, string, true, false, or null", and the quasi-BNF on the side of json.org is pretty clear that any of these things is a valid JSON value.
Beyond litigating the specification though, the current behaviour is just incredibly unhelpful. Javascript runtimes happily
parseandstringifynon-object and non-array "root" values, and OCaml programs need to deal with the same. To that end, I consistently carry around these functions so I can serialize JSON values as required by APIs and other programs (with the understanding my half-measure treatment of printing these atoms might actually be slightly off):Can we remove this limitation?