Returning JSON instead of string

26 views
Skip to first unread message

Carey Phillips

unread,
Feb 3, 2019, 1:43:06 AM2/3/19
to <swi-prolog@googlegroups.com>
I inherited some server code I don't fully understand and have been tasked with having it return JSON instead of plain strings. Here's what the current code looks like:

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_error)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_client)).
:- http_handler('/', web_form, []).

server(Port) :-
        http_server(http_dispatch, [port(Port)]).

web_form(_Request) :-
reply_html_page(
    title('POST demo'),
    [
       form([action='/', method='POST'], 
                [h1('Prolog Server')]
               )
        ]
    ).

:- http_handler('/dataexchange', dataexchange_handler, [time_limit(infinite)]).

dataexchange_handler(Request) :-
    member(method(post), Request), !,
    http_read_data(Request, DataString, []),
    general_predicate( DataString, OutString ),
    format('Content-type: text/html~n~n', []),
    portray_clause(OutString).

general_predicate( InString, Out ) :-
    term_string( TotalTerm, InString ),
    call_process_request( TotalTerm, ResultTerm ),
    term_string( ResultTerm, Out ).

The 'portray_clause' seems a bit kooky, but the current functionality definitely works (returning strings). I can construct SWIPL json objects using ResultTerm, but am not entirely sure what to do with them subsequently. 

Jan Wielemaker

unread,
Feb 3, 2019, 3:06:16 AM2/3/19
to Carey Phillips, <swi-prolog@googlegroups.com>
Call reply_json/1,2 or reply_json_dict/1,2 on them. That prints the
content header and formats the JSON. The entire idea behind the
SWI-Prolog http infrastructure is that you never need to do things with
strings. The libraries that care of serialization and parsing of
all common formats and all you need to do is the processing from
one nice Prolog term to the next.

For the dodgy part, if you want to exchange Prolog terms (as opposed to
JSON, which is faster and more versatile if both server and client speak
Prolog), use application/x-prolog as content type. If your client is
e.g., JavaScript, JSON is a much better choice. Prolog syntax is quite
hard to generate and parse reliably.

Cheers --- Jan
Reply all
Reply to author
Forward
0 new messages