JSON
There are several ways to work with JSON right now, that we'll unify and polish very soon.
#Unsafe Conversion
This emulates JavaScript's JSON conversion.
#Parse
Simply use the (last resort) special identity external:
RE[@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:
JSvar 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.
#Stringify
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
.
#Properly Use Js.Json
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.
#Higher-level Helpers
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!