在F#中创建复杂的nexted JSON对象的最佳和可读解决方案是什么?类似于以下JavaScript代码:
{
data: {
user: {
first_name:'myFirstName',
last_name:'myLastName',
address: {
street: 'myStreet'
}
},
type: 'user'
}
}
答案 0 :(得分:0)
Chiron是一个不错的JSON库https://github.com/xyncro/chiron
Json.parse """
{
"foo": [ { "bar": 1 }, { "bar": 2 }, { "bar": "fizz" } ],
"test": { "one":3.5, "two":null, "three":false }
}
"""
`结果 - >>
Object
(map
[("foo",
Array
[Object (map [("bar", Number 1M)]); Object (map [("bar", Number 2M)]);
Object (map [("bar", String "fizz")])]);
("test",
Object
(map [("one", Number 3.5M); ("three", Bool false); ("two", Null null)]))])
也可以与类型一起使用。
https://neoeinstein.github.io/blog/2015/12-15-chiron-taming-types-in-the-wild/index.html
https://neoeinstein.github.io/blog/2015/12-13-chiron-json-ducks-monads/index.html
答案 1 :(得分:0)
要序列化任何F#对象或对象/记录/联合列表等,我使用此代码(您可能需要填写/更正一些细节,因为我目前还没有完整的文件) :
open System.IO
type ResultInfo = { Result: string; ErrorMsg: string } // or use built-in Result type instead
// To install the Json.NET library, enter "Install-Package Newtonsoft.Json" in the Tools...NuGet Package Manager...Package Manager Console.
// let str = Newtonsoft.Json.JsonConvert.SerializeObject(...) throws an OutOfMemoryException for large collections, so use a StreamWriter instead.
let jsonSerializeToFile obj file =
try
(new FileInfo(file)).Directory.Create()
use writer = File.CreateText(file)
let ser = new Newtonsoft.Json.JsonSerializer()
ser.Formatting <- Newtonsoft.Json.Formatting.Indented
ser.Serialize(writer, obj)
{ Result = "ok"; ErrorMsg = None } // maybe return the length of the serialized string??
with
| ex -> { Result = "error"; ErrorMsg = Some <| ex.ToString() }
答案 2 :(得分:0)
使用FSharp.Data中的JsonValue,我喜欢这个:
let data =
( FSharp.Data.JsonValue.Record [|
"event", FSharp.Data.JsonValue.String eventName;
"properties", FSharp.Data.JsonValue.Record
(Array.append [|
"token", FSharp.Data.JsonValue.String token;
"distinct_id", FSharp.Data.JsonValue.String (distinctId())
|] param)
|])