title | description | canonical |
---|---|---|
JSON | Interacting with JSON in ReScript | /docs/manual/latest/json |
Bind to JavaScript's JSON.parse
and type the return value as the type you're expecting:
<CodeTab labels={["ReScript", "JS Output"]}>
// declare the shape of the json you're binding totypedata= {names: array<string>} // bind to JS' JSON.parse @scope("JSON") @valexternalparseIntoMyData: string=>data="parse"letresult=parseIntoMyData(`{"names": ["Luke", "Christine"]}`) letname1=result.names[0]
varresult=JSON.parse("{\"names\": [\"Luke\", \"Christine\"]}");varname1=result.names[0];
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. Slightly dangerous.
Use Js.Json.stringify
:
<CodeTab labels={["ReScript", "JS Output"]}>
Js.log(Js.Json.stringifyAny(["Amy", "Joe"]))
console.log(JSON.stringify(["Amy","Joe"]));
The Js.Json module provides slightly safer, low-level building blocks for power users who want to parse JSON on a per-field basis. See the examples in the API docs.