Rdflib,Python:是否有任何对象框架方法可以从图形a-la JSON-LD获取嵌套的dict / list结构?

Rdflib CONSTRUCT查询返回表示图形的元组列表.但是,模板语言通常最方便的是嵌套混合dicts和列表的树状结构(因为该结构与
HTML标记的树状结构很好地匹配).实际上,SELECT在这方面并不是更好,而是相同数据的非规范化版本.

提出一些临时转换很容易,但也许有一些惯用的方法给出图形和一些提示“枢轴”,产生一棵树?

例如,如果我们有一个包含Query和ResultVar个体的图形(带有数据属性,如标签等),那么树可以是带有ResultVar子节点的Query列表:

[
{'name': 'q1', 'uri': '...', 'children': 
  [{'name': 'x', 'value': '1', ... },
   {'name': 'y', 'value': '1', ... },
   ...
  ]},
...
]

为此,我们可能会提示使用Query – ResultVar顺序的方法.结果很容易使用嵌套的“循环”,它在模板中生成HTML标记.

我不喜欢重新发明轮子,我想这种问题不是唯一的,但我没有找到任何解决方案.

但是,我不想要ORM方法,因为它意味着在代码中有模式,我不想硬连线.

编辑:为了澄清可能的误解,Query / ResultVar只是一个例子.我可以使用Blog / Comment或Calendar / Event代替.

EDIT2
看起来这里正在寻找的是object framing,如JSON-LD中所使用的:

Framing is the process of taking a JSON-LD document, which expresses a graph of information, and applying a specific graph layout (called a Frame).

JSON-LD Framing allows developers to query by example and force a specific tree layout to a JSON-LD document.

所以,这里需要的是在rdflib,Python中构建框架的方法. This document(“JSON-LD:循环破坏和对象框架”)给出了一个流行的解释,我的问题正在寻找什么,但对于Python有类似的东西吗?

最佳答案 您可以通过SPARQLWrapper2类实现所要求的内容.可悲的是,至少可以理解它的
docs有点“复杂”.但是在
overall docs中有一个很好的例子:

from SPARQL import SPARQLWrapper2
queryString = "SELECT ?subj ?o ?opt WHERE { ?subj <http://a.b.c> ?o. OPTIONAL { ?subj <http://d.e.f> ?opt }}"
sparql = SPARQLWrapper2("http://localhost:2020/sparql")
# add a default graph, though that can also be in the query string
sparql.addDefaultGraph("http://www.example.com/data.rdf")
sparql.setQuery(queryString)
try :
    ret = sparql.query()
    print ret.variables  # this is an array consisting of "subj", "o", "opt"
        if (u"subj",u"prop",u"opt") in ret :
               # there is at least one binding covering the optional "opt", too
               bindings = ret[u"subj",u"o",u"opt"]
               # bindings is an array of dictionaries with the full bindings
               for b in bindings :
                       subj = b[u"subj"].value
                       o    = b[u"o"].value
                       opt  = b[u"opt"].value
                       # do something nice with subj, o, and opt
        # another way of accessing to values for a single variable:
        # take all the bindings of the "subj"
        subjbind = ret.getValues(u"subj") # an array of Value instances
        ...
except:
    deal_with_the_exception()

所以适应你的情况你可以使用children = ret.getValues(u’q1′).

点赞