Ocaml 如何使用Yojson更新JSON对象?
在阅读了一些示例之后,很容易通过Ocaml 如何使用Yojson更新JSON对象?,ocaml,Ocaml,在阅读了一些示例之后,很容易通过Yojson.Basic.from_string或from_channel构造JSON对象 另一方面,我们还可以通过pretty_to_string轻松地将JSON对象转换为字符串 但是,updateJSON对象很棘手,例如输入参数如下: { "content": "test content", "base" : { "version": 1, "id" : "a001" } } 我想更新其中的“id”,并
Yojson.Basic.from_string
或from_channel
构造JSON对象
另一方面,我们还可以通过pretty_to_string
轻松地将JSON对象转换为字符串
但是,update
JSON对象很棘手,例如输入参数如下:
{
"content": "test content",
"base" : {
"version": 1,
"id" : "a001"
}
}
我想更新其中的“id”
,并返回一个新的JSON对象:
{
"content": "test content",
"base" : {
"version": 1,
"id" : "a002"
}
}
let update_json (js: json) (key: string) (new_value: string) : json =
let rec aux (json_ele:json):json =
match json_ele with
| `Bool b -> `Bool b
| `Float f -> `Float f
| `Int i -> `Int i
| `List jl -> `List (List.map jl ~f:aux)
| `Null -> `Null
| `String st -> `String st
| `Assoc kvlist ->
`Assoc (
List.map
kvlist
~f:(fun (okey, ovalue) ->
match ovalue with
| `String v when okey = key -> (okey, `String new_value)
| _ -> (okey, aux ovalue)))
in
aux js
我试图编写一个函数来更新JSON对象:
{
"content": "test content",
"base" : {
"version": 1,
"id" : "a002"
}
}
let update_json (js: json) (key: string) (new_value: string) : json =
let rec aux (json_ele:json):json =
match json_ele with
| `Bool b -> `Bool b
| `Float f -> `Float f
| `Int i -> `Int i
| `List jl -> `List (List.map jl ~f:aux)
| `Null -> `Null
| `String st -> `String st
| `Assoc kvlist ->
`Assoc (
List.map
kvlist
~f:(fun (okey, ovalue) ->
match ovalue with
| `String v when okey = key -> (okey, `String new_value)
| _ -> (okey, aux ovalue)))
in
aux js
我想知道在Yojson中,编写上述函数是否是更新JSON对象的最佳方式?我不清楚“bug”是什么意思,但是
`Assoc
不需要字符串*JSON
,它需要(字符串*JSON)列表
。这意味着在您的`Assoc
案例中,您应该执行列表。map
:
| `Assoc pairs ->
List.map pairs ~f:(fun (okey, ovalue) ->
if okey = key then
key, new_value
else
okey, aux ovalue)
您可能需要将此函数分解并命名。对于更完整的问题,您能否更清楚地了解“bug”?还建议使用标准库而不是核心库,这样您的代码就不必为了尝试而修改。您可以通过处理
Bool,
Float f。。。使用默认设置(| u; as others->others),然后只关注需要每个特定处理的`列表和Àssoc。我也有一个帮助器库,你可以从中获得灵感Yojson repo中有一个问题: