问题描述
我正在尝试在 prolog 中创建这个谓词:
谓词json_get/3
可以定义为:json_get(JSON_obj, Fields, Result).
当Result
可恢复时为真按照Fields
(列表)中的字段链,从 JSON_obj
开始.一个领域由 N
表示(其中 N
主编号 o 等于 0)对应于JSON 数组的索引.
请帮助我理解遵循字段链.
谢谢
当然,所以 json 对象看起来像这样 '{"name" : "Aretha", "surname" : "Franklin"}'.如果我为此对象 prolog 调用 json_parse 谓词,请告诉我这个
json_obj([("name", "Aretha"), ("surname", "Franklin")])
,我们称这个obj为O
.p>
用json_get
我需要这样从O中提取名字,json_get(O, ["name"], R)
在某人的帮助下,现在这是谓词:
json_get(json_obj(JSON_obj), Field, Result) :-memberchk((字段,结果),JSON_obj).json_get(JSON_obj,字段,结果):-地图列表(json_get(JSON_obj),字段,结果).
所以现在问题是嵌套列表.例如这个输入
json_parse('{"nome" : "Zaphod",头":[头1",头2"]}',Z),json_get(Z,[头",1],R).
输出应该是 R = "Head2"
但谓词不提取字段并失败.
这是 json_parse 的输出
json_obj([("nome", "Zaphod"), ("heads", json_array(["Head1", "Head2"]))]).
这个怎么样
json_get(json_obj(Obj),[F|Fs],Res) :-成员((F,R),Obj),json_get(R,Fs,Res).json_get(json_array(Is),[N|Fs],Res) :-nth1(N,Is,R),json_get(R,Fs,Res).json_get(Res,[],Res).
这会在您的第二个示例中生成 Head1
而不是 Head2
.如果您不只是打错字,请解释这应该如何工作.(如果它是从零开始的,您只需将 nth1/3
更改为 nth0/3
.)
I'm tryung to create this predicate in prolog:
Please help me to understand to follow the chain of fields.
Thanks
edit1:
Of course, so json object looks like this '{"name" : "Aretha", "surname" : "Franklin"}'.if i call json_parse predicate to this object prolog show me this
json_obj([("name", "Aretha"), ("surname", "Franklin")])
, we call this obj O
.
with json_get
i need to extract from O the name in this way, json_get(O, ["name"], R)
edit2:
with someone's help this is the predicate now:
json_get(json_obj(JSON_obj), Field, Result) :-
memberchk((Field,Result), JSON_obj).
json_get(JSON_obj, Fields, Result) :-
maplist(json_get(JSON_obj), Fields, Result).
so now the problem is nested list.For example with this input
json_parse('{"nome" : "Zaphod",
"heads" : ["Head1", "Head2"]}', Z),
json_get(Z, ["heads", 1], R).
the output will should be R = "Head2"
but the predicate doesn't extract the field and fail.
edit3:
this is the output of json_parse
json_obj([("nome", "Zaphod"), ("heads", json_array(["Head1", "Head2"]))]).
How about this
json_get(json_obj(Obj),[F|Fs],Res) :-
member((F,R),Obj),
json_get(R,Fs,Res).
json_get(json_array(Is),[N|Fs],Res) :-
nth1(N,Is,R),
json_get(R,Fs,Res).
json_get(Res,[],Res).
This produces Head1
not Head2
in your 2nd example. Please explain how that is supposed to work, if you did not just make a typo. (If it is zero-based you can just change nth1/3
to nth0/3
.)
这篇关于json获取prolog谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!