Skip to content

Latest commit

 

History

History
69 lines (51 loc) · 1.76 KB

File metadata and controls

69 lines (51 loc) · 1.76 KB
title description canonical
JSON
Interacting with JSON in ReScript
/docs/manual/latest/json

JSON

Parse

Bind to JavaScript's JSON.parse and type the return value as the type you're expecting:

<CodeTab labels={["Reason (Old Syntax)", "ML (Older Syntax)", "JS Output"]}>

// declare the shape of the json you're binding to
type data = {names: array(string)};

// bind to JS' JSON.parse
[@bs.scope "JSON"] [@bs.val]
external parseIntoMyData: string => data = "parse";

let result = parseIntoMyData({|{"names": ["Luke", "Christine"]}|});
let name1 = result.names[0];
(* declare the shape of the json you're binding to *)
type data = {names: string array}

(* bind to JS' JSON.parse *)
external parseIntoMyData: string -> data = "parse"
[@@bs.scope "JSON"] [@@bs.val]

let result = parseIntoMyData {|{"names": ["Luke", "Christine"]}|}
let name1 = (result.names).(0)
var result = JSON.parse("{\"names\": [\"Luke\", \"Christine\"]}");
var name1 = 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 Js.Json.stringify:

<CodeTab labels={["Reason (Old Syntax)", "ML (Older Syntax)", "JS Output"]}>

Js.log(Js.Json.stringifyAny([|"Amy", "Joe"|]));
Js.log (Js.Json.stringifyAny [|"Amy"; "Joe"|])
console.log(JSON.stringify([
  "Amy",
  "Joe"
]));

Advanced

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.