如何在 Prolog 中读取 JSON 文件

How to read JSON file in Prolog

我发现一些关于相关问题的 SO 帖子没有帮助。我终于弄明白了,下面是如何读取 .json 文件的内容。假设路径是/home/xxx/dnns/test/params.json,我想把.json里面的字典变成Prolog字典:

{
    "type": "lenet_1d",
    "input_channel": 1,
    "output_size": 130,
    "batch_norm": 1,
    "use_pooling": 1,
    "pooling_method": "max",
    "conv1_kernel_size": 17,
    "conv1_num_kernels": 45,
    "conv1_stride": 1,
    "conv1_dropout": 0.0,
    "pool1_kernel_size": 2,
    "pool1_stride": 2,
    "conv2_kernel_size": 12,
    "conv2_num_kernels": 35,
    "conv2_stride": 1,
    "conv2_dropout": 0.514948804688646,
    "pool2_kernel_size": 2,
    "pool2_stride": 2,
    "fcs_hidden_size": 109,
    "fcs_num_hidden_layers": 2,
    "fcs_dropout": 0.8559119274655482,
    "cost_function": "SmoothL1",
    "optimizer": "Adam",
    "learning_rate": 0.0001802763794651928,
    "momentum": null,
    "data_is_target": 0,
    "data_train": "/home/xxx/data/20180402_L74_70mm/train_2.h5",
    "data_val": "/home/xxx/data/20180402_L74_70mm/val_2.h5",
    "batch_size": 32,
    "data_noise_gaussian": 1,
    "weight_decay": 0,
    "patience": 20,
    "cuda": 1,
    "save_initial": 0,
    "k": 4,
    "save_dir": "DNNs/20181203090415_11_created/k_4"
}

要使用 SWI-Prolog 读取 JSON 文件,请查询

?- use_module(library(http/json)). % to enable json_read_dict/2
?- FPath = '/home/xxx/dnns/test/params.json', open(FPath, read, Stream), json_read_dict(Stream, Dicty).

你会得到

FPath = 'DNNs/test/k_4/model_params.json',
Stream = <stream>(0x7fa664401750),
Dicty = _12796{batch_norm:1, batch_size:32, conv1_dropout:0.
0, conv1_kernel_size:17, conv1_num_kernels:45, conv1_stride:
1, conv2_dropout:0.514948804688646, conv2_kernel_size:12, co
nv2_num_kernels:35, conv2_stride:1, cost_function:"SmoothL1"
, cuda:1, data_is_target:0, data_noise_gaussian:1, data_trai
n:"/home/xxx/Downloads/20180402_L74_70mm/train_2.h5", data
_val:"/home/xxx/Downloads/20180402_L74_70mm/val_2.h5", fcs
_dropout:0.8559119274655482, fcs_hidden_size:109, fcs_num_hi
dden_layers:2, input_channel:1, k:4, learning_rate:0.0001802
763794651928, momentum:null, optimizer:"Adam", output_size:1
30, patience:20, pool1_kernel_size:2, pool1_stride:2, pool2_
kernel_size:2, pool2_stride:2, pooling_method:"max", save_di
r:"DNNs/20181203090415_11_created/k_4", save_initial:0, type
:"lenet_1d", use_pooling:1, weight_decay:0}.

其中 Dicty 是所需的词典。

如果你想将其定义为谓词,你可以这样做:

:- use_module(library(http/json)).

get_dict_from_json_file(FPath, Dicty) :-
  open(FPath, read, Stream), json_read_dict(Stream, Dicty), close(Stream).

即使是 40 年前发布的 DEC10 Prolog 也可以处理 JSON 就像一个正常的术语。 JSON 不需要专门的库或解析器,因为 Prolog 可以直接解析它。

?- X={"a":3,"b":"hello","c":undefined,"d":null} .                                   
X = {"a":3, "b":"hello", "c":undefined, "d":null}.                                                                            
?-