Skip to content

Latest commit

 

History

History
82 lines (57 loc) · 1.96 KB

File metadata and controls

82 lines (57 loc) · 1.96 KB
titledescriptioncanonical
JSON
Interacting with JSON in ReScript
/docs/manual/v11.0.0/json

JSON

Parse

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.

Stringify

Use JSON.stringify if your data is of type JSON.t or JSON.stringifyAny if it is not.

<CodeTab labels={["ReScript", "JS Output"]}>

Console.log(JSON.stringifyAny(["Amy", "Joe"]))
console.log(JSON.stringify(["Amy","Joe"]));

Import a JSON file

Use the @module attribute to import JSON files directly.

<CodeTab labels={["ReScript", "JS Output (Module)", "JS Output (CommonJS)"]}>

@moduleexternalstudentNames: JSON.t="./students.json"Console.log(studentNames)
import*asStudentsJsonfrom"./students.json";varstudentNames=StudentsJson;console.log(studentNames);
varStudentsJson=require("./students.json");varstudentNames=StudentsJson;console.log(studentNames);

Advanced

Thanks to untagged variants, JSON can be encoded and decoded idiomatically. Check it out on the variants page.

close