title |
---|
JSON |
There are several ways to work with JSON right now, that we'll unify and polish very soon.
This emulates JavaScript's JSON conversion.
Simply use the (last resort) special identity external:
type data = {name: string} [@@bs.deriving abstract]
external parseIntoMyData : string -> data = "parse" [@@bs.scope "JSON"][@@bs.val]
let result = parseIntoMyData "{\"name\": \"Luke\"}"
let n = result |. name
[@bs.deriving abstract]
type data = {name: string};
[@bs.scope "JSON"] [@bs.val]
external parseIntoMyData : string => data = "parse";
let result = parseIntoMyData("{\"name\": \"Luke\"}");
let n = nameGet(result);
Output:
var result = JSON.parse("{\"name\": \"Luke\"}");
var n = result.name;
Where data
can be any type you assume the JSON is. As you can see, this compiles to a straightforward JSON.parse
call. As with regular JS, this is convenient, but has no guarantee that e.g. the data is correctly shaped, or even syntactically valid.
Since JSON.stringify is slightly safer than JSON.parse
, we've provided it out of the box in Js.Json. It compiles to JSON.stringify
.
Technically, the correct way to handle JSON is to recursively parse each field, and handle invalid data accordingly. Js.Json provides such low-level building blocks. See the examples in the API docs.
We have a community-maintaned, pseudo-official JSON helper library called bs-json. Those interested in combinators can also check out JsonCodec. Both provide more convenient JSON parsing/printing helpers that leverage the previous section's low-level API.
We'll provide a better, first-party solution to JSON too in the future. Stay tuned!