问题
I'm tryung to create this predicate in prolog:
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.
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"]))]).
回答1:
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
.)
来源:https://stackoverflow.com/questions/48153619/json-get-prolog-predicate