开发者

Printing/Parsing JSON object from RDF query result

I'm trying to parse a result from an SPARQL query from Sesame. I found sample code, the relevant part below, and I'm showing my result below.

(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" }

           },

           {

       开发者_Python百科        "costar": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.timothy_daly" },

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

           },


      ]

   }

}     

But I get this error:

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 . . .

How can I change the "print" statement?

What I want to see is something like the costar and movie name on the same line:

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

Later, I'll strip off the namespaces.

Thanks!


The error you a receiving indicates that the result dictionary has no key 'type'. If you check carefully, each element of results['results']['bindings'] is a dictionary with two keys: 'costar' and 'movie', so your result variable will be a dictionary with these two keys.

Each of result['costar'] and result['movie'] is also a dictionary with two keys: 'type' and 'value'. What you really want is to build a string containing result['costar']['value'] and result['movie']['value'] separated by a space. Given a single result you can achieve this with:

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

Now to print a string containing all the costars and movies separated by newlines you just need to modify your print statement to

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


Take a look to the sample code of the SPARQLWrapper:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜