Can json_write_dict/2 write an array of dicts?

Needed to create the file style.json (ref)

File: style.json

[
    {
        "selector": "node",
        "style": {
            "label": "data(id)"
        }
    },
    {
        "selector": "edge",
        "style": {
            "curve-style": "haystack"
        }
    }
]

and wanted to use json_write_dict/2.

The signature of json_write_dict/2 is json_write_dict(+Stream, +Dict) is det which lead me to believe that it could only write a single dict.

In working on style.json went the other direction to convert the JSON back to a SWI-Prolog dictionary and it worked. Then converted that back into JSON and it worked.

?- example_01:style_dict(Dicts),json:json_write_dict(current_output,Dicts).
[
  {"selector":"node", "style": {"label":"data(id)"}},
  {"selector":"edge", "style": {"curve-style":"haystack"}}
]
Dicts = ['$VAR'('_'){selector:node, style:'$VAR'('_'){label:'data(id)'}}, '$VAR'('_'){selector:edge, style:'$VAR'('_'){'curve-style':haystack}}].

Along the way noticed the it was not a single SWI-Prolog dictionary but was an array of SWI-Prolog dictionaries.

Looking at the documentation more closely noticed

Write a JSON term, represented using dicts. This is the same as json_write/3, but assuming the default representation of JSON objects as dicts.

What a difference a single s makes.

So the question is:

Is using json_write_dict/2 with an array of dicts a feature or a bug? I take it that it is a feature but would hate to start using it this way only to learn it is a bug.

The +Dict is a bit misleading. It takes any JSON value in Prolog notation, so also strings, boolean, etc. A Prolog list is mapped to a JSON array.

1 Like