array a makes a JSON array of the Js.Json.t arraya
The functions below are specialized for specific array type which happened to be already JSON object in the Melange runtime. Therefore they are more efficient (constant time rather than linear conversion).
parseExn s parses the string s into a JSON data structure
Returns a JSON data structure
raisesSyntaxError
if given string is not a valid JSON. Note SyntaxError is a JavaScript exception.
(* parse a simple JSON string *)
let json =
try
Js.Json.parseExn {| "foo" |}
with
| _ -> failwith "Error parsing JSON string"
in
match Js.Json.classify json with
| Js.Json.JSONString value -> Js.log value
| _ -> failwith "Expected a string"
(* parse a complex JSON string *)
let getIds s =
let json =
try
Js.Json.parseExn s
with
| _ -> failwith "Error parsing JSON string"
in
match Js.Json.classify json with
| Js.Json.JSONObject value ->
(* In this branch, compiler infer value : Js.Json.t Js.Dict.t *)
begin match Js.Dict.get value "ids" with
| Some ids ->
begin match Js.Json.classify ids with
| Js.Json.JSONArray ids ->
(* In this branch compiler infer ids : Js.Json.t array *)
ids
| _ -> failwith "Expected an array"
end
| None -> failwith "Expected an `ids` property"
end
| _ -> failwith "Expected an object"
(* prints `1, 2, 3` *)
let _ =
Js.log (getIds {| { "ids" : [1, 2, 3] } |})