简体   繁体   中英

How can I convert SPARQL query into JSON format?

This is my code

#!/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")

and this is the output that I get:

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

How do I convert the file to JSON format for my further analysis? I have read that there is an inbuilt method to convert from SPARQL to JSON. How can I do that?

Well, I figured it out!

I just had to use json.dumps(json query,filename) to put the output in JSON format!

I'd strongly recommend to use SPARQLWrapper instead of trying to implement all the specifics of making a proper SPARQL request yourself. It's for example possible that your SPARQL endpoint doesn't "speak" application/sparql-results+json . SPARQLWrapper would correctly handle this for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM