请评论如何在ReasonML中解码GeoJson文件?我尝试在解码器中解码没有“字段纬度和经度”的坐标,但我找不到如何在JSON文件中解析字段坐标的任何信息。
GeoJson文件
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
131.469670264,
33.3158712032
]
},
"properties": {
"index": 0,
"alias": "海地獄-別府市",
"name": "Umi-Jigoku",
"image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/7T1aXG9Q3CAtEbwqFm3Nlw/o.jpg"
}ReasonML中的JsonDecoder (bs-json)
[@genType]
type properties = {
index: int,
alias: string,
name: string,
image_url: string,
geometry: coordinates,
}
and coordinates = {
latitude: float,
longitude: float,
};
let places = "../json/alljapan.json";
module Decode = {
let coordinates = json =>
Json.Decode.{
latitude: json |> field("latitude", float),
longitude: json |> field("longitude", float),
};
let properties = json =>
Json.Decode.{
index: json |> field("index", int),
alias: json |> field("alias", string),
name: json |> field("name", string),
image_url: json |> field("image_url", string),
geometry: json |> field("geometry", coordinates),
};
};
let line = places |> Json.parseOrRaise |> Decode.line;发布于 2019-12-23 02:22:34
在工作中,我们编写了一个名为GeoReason的库,目标是在RFC-7946 spec之后为GeoJSON数据结构提供原因类型、构造函数、编码器和解码器(以及一些辅助函数,如eq)。
我还没有尝试将该库与React Native一起使用,但我假设它应该可以在任何可以将Reason编译为JS的地方工作。
概述
Js.Dict.t(Js.Json.t)用法
假设您有一个Js.Json.t类型的JSON值,并且您已经按照自述文件中的说明安装了GeoReason,您可以这样解码和使用您的数据:
// this is a `Belt.Result` that is either `Ok` with the GeoJSON data, or
// Error with information describing what went wrong while decoding
let decoded = GeoJSON.decode(myFileData);
switch (decoded) {
| Error(parseError) =>
Decode.ParseError.failureToDebugString(parseError) |> Js.log;
// if the GeoJSON value is a "Feature", it may have the following fields,
// but note that technically all of them are optional according to the spec.
// if you want to decode the dictionary of properties, you can do so here
| Ok(GeoJSON.Feature({id, geometry, properties})) =>
properties
->Belt.Option.flatMap(dict => Js.Dict.get(dict, "image_url"))
->Belt.Option.flatMap(json => Js.Json.decodeString(json))
->Belt.Option.map(url => /* do something with the url? */);
| Ok(Geometry(Point({latlong, altitude})) =>
/* use latitude and longitude? */
| Ok(Geometry(Polygon(data))) => /* ... */
| Ok(_) =>
// lots more cases to handle, like line geometries,
// geometry collections, feature collections, etc...
};正如您所看到的,匹配GeoJSON值可能涉及的所有内容是一个相当复杂的过程,因此它有点取决于您希望如何处理这些值。我已经向库中添加了一些辅助函数,比如GeoJSON.getPolygons,它将尝试获取任何类型GeoJSON值的多边形列表(如果没有多边形,则返回一个空列表)。如果有其他有用的帮助器,请随时打开问题。
发布于 2019-12-23 04:53:33
您可能应该使用GeoReason,正如@mlms13建议的那样,但是如果您仍然希望使用bs-json自己解码它,您可以利用BuckleScript中元组作为数组实现的事实,并使用pair解码器来获取值,然后将其转换为您的记录类型:
let coordinates = json =>
Json.Decode.(
pair(float, float)
|> map(((latitude, longitude)) => {latitude, longitude})
);https://stackoverflow.com/questions/59442145
复制相似问题