Created
August 12, 2017 18:45
-
-
Save jasim/36afd48215a527d83b1fb2e25952e3af to your computer and use it in GitHub Desktop.
Reason script to traverse a native JSON object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type json = Js.Json.t; | |
let x: json = [%bs.raw {|{"a": [1, "hello", 2, {"b": {"c": [100,200, "d", [10,20,30]]}}]}|}]; | |
let rec json_to_string json => { | |
let array_to_string a => a |> Array.to_list |> String.concat ","; | |
let emitObject o => | |
"{" ^ | |
{ | |
let emitKV (key, value) => key ^ ": " ^ json_to_string value; | |
let dict = Js.Dict.entries o; | |
array_to_string (Array.map emitKV dict) | |
} ^ "}"; | |
let emitArray a => "[" ^ array_to_string (Array.map json_to_string a) ^ "]"; | |
switch (Js.Json.classify json) { | |
| JSONNull => "null" | |
| JSONTrue => "true" | |
| JSONFalse => "false" | |
| JSONNumber n => string_of_float n | |
| JSONString s => "\"" ^ s ^ "\"" | |
| JSONArray a => emitArray a | |
| JSONObject o => emitObject o | |
} | |
}; | |
Js.log (json_to_string x); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment