如何从Prolog中的Json字符串中的字段获取值?

时间:2016-12-14 12:22:25

标签: json swi-prolog

我正在开发一个Prolog项目,该项目可以从omdb api回答关于电影和系列的问题。

我用它来返回包含电影或系列信息的完整Json字符串:

findMovie(X,Json):-
    atomic_list_concat(X, ',', Atom),
    uri_query_components(QS, [t=Atom]) %t is the title of the movie
    format(atom(HREF),'http://www.omdbapi.com/?~s',[QS]),
    http_get(HREF,Json, []),
    write(Json).

如果我搜索以下内容:" Fantastic Beasts&#34 ;,写(Json)将在控制台中打印以下内容:

{"Title":"Fantastic Beasts and Where to Find Them",
"Year":"2016",
"Rated":"PG-13",
"Released":" 2016",
"Runtime":"133 min",
"Genre":"Adventure, Family, Fantasy",
"Director":"David Yates","WriJ.K. Rowling",
"Actors":"Eddie Redmayne, Sam Redford, Scott Goldman, Tim Bentinck",
"Plot":"Thetures of writer Newt Scamander in New York's secret community of witches and wizards seventy before Harry Potter reads his book in school.",
"Language":"English",
"Country":"UK, USA","Awards":"1 nomination.",
"Poster":"https://images-na.ssl-images-amazon.com/images/M/MV5BMjMxOTM1OTI4MV5BBnXkFtZTgwODE5OTYxMDI@._V1_SX300.jpg",
"Metascore":"66",
"imdbRating":"7.9",
"imdbVotes":"75,816bID":"tt3183660",
"Type":"movie",
"Response":"True"}

如何返回值?例如:"年"的价值这是2016年。我已经阅读了一些关于将Json字符串转换为Prolog格式的内容,但我无法弄明白。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

findMovie(X,Json):-
    Field = 'Year',
    atomic_list_concat(X, ',', Atom),
    uri_query_components(QS, [t=Atom]) %t is the title of the movie
    format(atom(HREF),'http://www.omdbapi.com/?~s',[QS]),
    http_get(HREF,json(Json), []),   %json(Json) converts it to Prolog terms.
    member(Field=Result,Json),    %Result will get the value of 'Year'
    write(Result).