Search code examples
jsonprologswi-prolog

Get value from JSON object in Prolog


I have two questions.

  • How can I access the values in a JSON data structure in Prolog?
  • How can I yield a list of solutions from a predicate as JSON?

My Code:

handle(Request) :-
   format(user_output,"I'm here~n",[]),
   http_read_json(Request, DictIn,[json_object(term)]),
   %beat(DictIn.name,DictIn.move,X),
   %get list of solution of beat in to JSON and keep it in DictOut
   reply_json(DictOut).

Solution

  • I assume you are using SWI Prolog. Your code suggests that you want to convert JSON to SWI Prolog dicts. So you need to change

    http_read_json(Request, DictIn, [json_object(term)])

    to

    http_read_json(Request, DictIn, [json_object(dict)]),

    or you can just use http_read_json_dict/2. Note that Request must be a PUT or POST request or else these predicates will throw a domain_error(Type, Term).

    You can print out DictIn to take a look at what fields you want to extract.

    For the response use reply_json_dict/{1, 2}.