json_read_dict example

133 views
Skip to first unread message

Bambang Purnomosidi D. P.

unread,
Jul 16, 2014, 9:20:01 AM7/16/14
to swi-p...@googlegroups.com
Dear all,

This one is probably trivial but I don't know how to solve it. I try to read a JSON file and get one of its value:

file.json
-----------

{ "port": 8080 }

Then I want to get the value of "port", using swipl REPL below:

?- open('file.json',read,X).
X = <stream>(0x882d3f8).

?- use_module(library(http/json)).
true.

?- json_read_dict(X,Config).
ERROR: get_code/2: Arguments are not sufficiently instantiated
?-

Any help / pointer is appreciated.

Thank you.

Jan Wielemaker

unread,
Jul 16, 2014, 9:42:47 AM7/16/14
to Bambang Purnomosidi D. P., swi-p...@googlegroups.com
Variables are not shared between interactive goals. So,

1 ?- use_module(library(http/json)).
true.

2 ?- open('file.json',read,X), json_read_dict(X,Config), close(X).
X = <stream>(0xf16b70),
Config = _G1894{port:8080}.

If you do this in a program, use something like this:

file_json(File, JSON) :-
setup_call_cleanup(
open(File, read, In),
json_read_dict(In, JSON),
close(In)).

Using setup_call_cleanup/3 you don't have to worry about leaking stream
handles, no matter what happens.

Cheers --- Jan

P.s. You can refer to old toplevel variables in a new query using
$X instead of plain X. This however is only a shorthand for
interactive usage.


>
> Thank you.
>
> --
> You received this message because you are subscribed to the Google
> Groups "SWI-Prolog" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to swi-prolog+...@googlegroups.com
> <mailto:swi-prolog+...@googlegroups.com>.
> Visit this group at http://groups.google.com/group/swi-prolog.
> For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages