Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse this JSON to a record type?

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.

like image 874
Bradford Avatar asked Apr 30 '17 00:04

Bradford


People also ask

How do I parse a JSON file?

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.

What data type does JSON parse return?

The JSON. parse() method parses a string and returns a JavaScript object. The string has to be written in JSON format.

Can we extract the data from JSON file?

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.

What is a record in JSON?

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.


1 Answers

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)
  };
like image 127
glennsl Avatar answered Oct 07 '22 12:10

glennsl