Print / parse JSON object from RDF query result

I am trying to parse the result from a SPARQL query from Sesame. I found a code sample, the corresponding part below, and I show 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" }

           },

           {

               "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 looks like the name costar and movie on the same line:

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

Later I will remove the namespace.

Thank!

+3
source share
2 answers

The error you get indicates that the dictionary resultdoes not have a key 'type'. If you check carefully, each element results['results']['bindings']is a dictionary with two keys: 'costar'and 'movie', therefore, your variable resultwill be a dictionary with these two keys.

result['costar'] result['movie'] : 'type' 'value'. , result['costar']['value'] result['movie']['value'], . result, :

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

, , , ,

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

SPARQLWrapper:

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

All Articles