如何将SPARQL查询转换为JSON格式?

时间:2015-03-18 18:59:46

标签: json rdf sparql rdflib sparqlwrapper

这是我的代码

#!/usr/bin/python
# -*- coding: utf-8 -*-

import requests
from requests.auth import HTTPBasicAuth
from abc import ABCMeta, abstractmethod

class PPTSparqlClient:

    """Minimal Class to access PPT SparqlEndpoints"""

    def __init__(self, endpoint, user, passw):
        self.endpoint = endpoint;
        self.user = user;
        self.passw = passw;
        self.defaultHeaders = { "accept":"application/sparql-results+json" }
        self.defaultAuth = HTTPBasicAuth(self.user, self.passw)

    def execute(self, query, handler=None):
        r = requests.get(self.endpoint, auth=self.defaultAuth, headers=self.defaultHeaders, params={"query":query})
        if (r.status_code==404):
            raise Exception("404 : not found " + self.endpoint);        
        if (r.status_code==401):
            raise Exception("401 : unauthorized " + self.user + " " + self.passw)
        if(handler==None):
            return r.json();
        else:
            j = r.json();
            handler.startQueryResult(j["head"]["vars"]);
            for bindingSet in j["results"]["bindings"]:
                handler.handleSolution(bindingSet);
            handler.endQueryResult();

class TupleQueryResultHandler:

    """Base Class of SPARQL SELECT Query handlers"""

    @abstractmethod
    def startQueryResult(self,heads):
        pass;
    @abstractmethod
    def handleSolution(self,bindingSet):
        pass;
    @abstractmethod
    def endQueryResult(self):
        pass;        

class TerminalPrinter(TupleQueryResultHandler):

    """Class to handle application/sparql-results+json results by printing them to the terminal"""    

    def startQueryResult(self,heads):
        self.heads = heads;
        for head in heads:
            print "binding:"+head;
        print ""

    def handleSolution(self,bindingSet):
        for head in self.heads:
            print head+":"+bindingSet[head]["value"];
        print "";



def main(endpoint, user, passw, query):
    client = PPTSparqlClient(endpoint,user,passw);
    try:
        client.execute(query, TerminalPrinter());
    except Exception as ex:
        print ex.message


endpoint = "http://termmanagement.poolparty.biz/PoolParty/sparql/LawEnforcementSmall";
user = "username";
passw = "pass";

if  __name__ =='__main__':
    main(endpoint,user,passw,"SELECT * WHERE { ?s ?p ?o } LIMIT 10")

这是我得到的输出:

binding:s
binding:p
binding:o

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://www.w3.org/1999/02/22-rdf-syntax-ns#type
o:http://rdfs.org/ns/void#Dataset

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/creator
o:doanem

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/language
o:en

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://www.semantic-web.at/ppcl/availablelanguages
o:en

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/date
o:2015-01-27T16:28:21Z

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/subject
o:video management

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/title
o:Law Enforcement

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://rdfs.org/ns/void#sparqlEndpoint
o:http://termmanagement.poolparty.biz/PoolParty/sparql/LawEnforcement

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://rdfs.org/ns/void#feature
o:node19dtn3sgfx1

s:node19dtn3sgfx1
p:http://www.w3.org/1999/02/22-rdf-syntax-ns#type
o:http://rdfs.org/ns/void#TechnicalFeature

如何将文件转换为JSON格式以供进一步分析?我已经读过有一种内置方法可以从SPARQL转换为JSON。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

好吧,我明白了!

我只需要使用json.dumps(json query,filename)将输出放在JSON格式中!

答案 1 :(得分:0)

我强烈建议您使用SPARQLWrapper,而不是尝试实现自己制作正确的SPARQL请求的所有细节。例如,您的SPARQL端点可能不会“说”application/sparql-results+json。 SPARQLWrapper会为您正确处理此问题。