paul tarvydas
paul tarvydas

Reputation: 113

SWI-Prolog syntax for JSON

json([ name='Demo term',
       created=json([day= @null, month='December', year=2007]),
       confirmed= @true,
       members=[1, 2, 3]
     ])

I'm staring at the swi prolog manual and don't understand bits of the syntax (https://linkedpolitics.project.cwi.nl/swish/pldoc/man?section=jsonsupport) and I can't figure out the appropriate search terms. What does this mean? name='Demo term', And this? [day= @null And this? members=[1, 2, 3] Are these bits of special syntax or simply weird atoms?

Upvotes: 1

Views: 134

Answers (1)

David Tonhofer
David Tonhofer

Reputation: 15316

There is nothing special about this syntax really:

json/1 is a compound term with list as only paramter.

That list has entries

  • name='Demo term'
  • created=json([day= @null, month='December', year=2007])
  • confirmed= @true
  • members=[1, 2, 3]

evidently trying to emulate a map keyword -> value:

  • The keyword name is associated to the atom 'Demo term' (in single quotes because it contains a space and starts with uppercase
  • The keyword created is associated with the complex compound term json([day= @null, month='December', year=2007])
  • The keyword confirmed is associated with the compound term @true, better written @(true).
  • The keyword member is associated with the list [1,2,3]

Note this description at https://eu.swi-prolog.org/pldoc/man?section=jsonsupport

The JSON constants true and false are mapped -like JPL- to @(true) and @(false). The JSON constant null is mapped to the Prolog term @(null)

Although one has to write

X='@'(true).

so maybe the example is foobared.

You can do this at the command line of SWI-Prolog to print the term in canonical mode (added newlines for readability; it is my contention that write_canonical should also indent properly which it sadly does not):

?- write_canonical(json([ name='Demo term',
|           created=json([day= '@'(null), month='December', year=2007]),
|           confirmed= '@'(true),
|           members=[1, 2, 3]
|         ])).
json([=(name,'Demo term'),
      =(created,json(
                  [=(day,@(null)),
                   =(month,'December'),
                   =(year,2007)]
                )
       ),
      =(confirmed,@(true)),
      =(members,[1,2,3])])
true.

Upvotes: 2

Related Questions