从RDF查询结果打印/解析JSON对象

时间:2011-05-08 20:14:50

标签: python json parsing printing rdflib

我正在尝试解析来自Sesame的SPARQL查询的结果。 我找到了示例代码,下面的相关部分,我在下面显示了我的结果。

(response, content) = httplib2.Http().request(endpoint, 'POST', urllib.urlencode(params), headers=headers)

print "Response %s" % response.status
results = json.loads(content)
print "\n".join([result['type']['value'] for result in results['results']['bindings']])

{

   "head": {

       "vars": [ "costar", "movie" ]

   },

   "results": {

       "bindings": [

           {

               "costar": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.connie_nielsen" },

               "movie": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.basic_2003" }

           },

           {

               "costar": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.timothy_daly" },

               "movie": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.basic_2003" }

           },


      ]

   }

}     

但是我收到了这个错误:

Traceback (most recent call last):
  File "C:\Software\rdflib\movieSparqlQuery.py", line 45, in <module>
    print "\n".join([result['type']['value'] for result in results['results']['b
indings']])
KeyError: 'type'
Press any key to continue . . .

如何更改“打印”声明?

我希望看到的是同一行中的costar和电影名称:

http://rdf.freebase.com/ns/en.connie_nielsen  http://rdf.freebase.com/ns/en.basic_2003

稍后,我将剥离名称空间。

谢谢!

2 个答案:

答案 0 :(得分:2)

您收到的错误表明result字典没有密钥'type'。如果仔细检查,results['results']['bindings']的每个元素都是一个包含两个键的字典:'costar''movie',因此您的result变量将是包含这两个键的字典。< / p>

result['costar']result['movie']中的每一个也都是一个包含两个键的词典:'type''value'。你真正想要的是建立一个由空格分隔的result['costar']['value']result['movie']['value']字符串。给定一个result,您可以通过以下方式实现此目的:

" ".join(result[var]['value'] for var in results['head']['vars'])

现在打印一个字符串,其中包含由换行符分隔的所有costars和电影,您只需将print语句修改为

print "\n".join([" ".join(result[var]['value'] for var in results['head']['vars']) for result in results['results']['bindings']])

答案 1 :(得分:0)

查看SPARQLWrapper的示例代码:

for result in results["results"]["bindings"]:
    print(result["label"]["value"])