json获取序言谓词 [英] json get prolog predicate
问题描述
我正在尝试在序言中创建此谓词:
I'm tryung to create this predicate in prolog:
谓词
json_get/3
可以定义为:json_get(JSON_obj, Fields, Result).
,当Result
可通过以下方式恢复时为true 从JSON_obj
开始的Fields
(列表)中的字段链.一个领域 用N
表示(N
主数o等于0)表示与 JSON数组的索引.
The predicate
json_get/3
can be defined as:json_get(JSON_obj, Fields, Result).
which is true whenResult
is recoverable by following the chain of fields inFields
(a list) starting fromJSON_obj
. A field represented byN
(withN
a major number o equal to 0) corresponds to an index of a JSON array.
请帮助我了解遵循字段链的方法.
Please help me to understand to follow the chain of fields.
谢谢
edit1:
当然,因此json对象看起来像这样的"{{name":"Aretha","surname":"Franklin"}". 如果我将此对象的序言调用json_parse谓词显示给我
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)])
,我们称为obj O
.
json_obj([("name", "Aretha"), ("surname", "Franklin")])
, we call this obj O
.
使用json_get
我需要以这种方式从O中提取名称json_get(O, ["name"], R)
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).
输出应为R = "Head2"
,但谓词不会提取该字段并失败.
the output will should be R = "Head2"
but the predicate doesn't extract the field and fail.
edit3:
这是json_parse的输出
this is the output of json_parse
json_obj([("nome", "Zaphod"), ("heads", json_array(["Head1", "Head2"]))]).
推荐答案
如何解决
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).
这将在您的第二个示例中生成Head1
而不是Head2
.如果您不只是打错字,请说明该怎么做. (如果它是从零开始的,则可以将nth1/3
更改为nth0/3
.)
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获取序言谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!