I have some data I'll be fetching at runtime:
/* {id: 1, name: 'brad', age: 27, address: { city: 'city1', state: 'state1' } } */
let data = "{\"id\":1,\"name\":\"brad\",\"age\":27,\"address\":{\"city\":\"city1\",\"state\":\"state1\"}}";
Using ReasonML and BuckleScript, how can I can get this data in the form:
type address = {
city: string,
state: string
};
type person = {
id: int,
name: string,
age: option int,
address: option address
};
The solution I've come up with are 100s of lines long.
If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.
The JSON. parse() method parses a string and returns a JavaScript object. The string has to be written in JSON format.
To extract the name and projects properties from the JSON string, use the json_extract function as in the following example. The json_extract function takes the column containing the JSON string, and searches it using a JSONPath -like expression with the dot . notation. JSONPath performs a simple tree traversal.
Describes a list of data fields (as name/value pairs), a data table schema and nested data records (if any) for one or more data records.
Using bs-json:
let parseAddress json =>
Json.Decode.{
city: json |> field "city" string,
state: json |> field "state" string
};
let parsePerson json =>
Json.Decode.{
id: json |> field "id" int,
name: json |> field "name" string,
age: json |> optional (field "age" int),
address: json |> optional (field "address" parseAddress)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With