I am trying to convert the RDF/XML format to JSON format. Is there any python (library) example that i can look into for this to do ?
Asked
Active
Viewed 3,357 times
4
-
In case you are here because of the plain title of the question. Look here for a java solution http://stackoverflow.com/questions/43638342 – jschnasse May 19 '17 at 11:08
2 Answers
9
You can use rdflib to parse many RDF variants (including RDF/XML), or maybe the simpler rdfparser if it suits your needs. You can then use the standard library Python json
module (or equivalently third-party simplejson
if you're using some Python version older than 2.6) to serialize the in-memory structure built with the parser into JSON. I'm not familiar with any package embodying both steps, unfortunately.
With the example at rdfparser's site, the overall work would be just...:
import rdfxml
import json
class Sink(object):
def __init__(self): self.result = []
def triple(self, s, p, o): self.result.append((s, p, o))
def rdfToPython(s, base=None):
sink = Sink()
return rdfxml.parseRDF(s, base=None, sink=sink).result
s_rdf = someRDFstringhere()
pyth = rdfToPython(s_rdf)
s_jsn = json.dumps(pyth)

Alex Martelli
- 854,459
- 170
- 1,222
- 1,395
1
For those coming to this question recently, rdflib since version 6.0 supports JSON-LD output directly:
from rdflib import Graph
g = Graph()
g.parse("demo.xml")
print g.serialize(format='json-ld')

Brendan Quinn
- 2,059
- 1
- 19
- 22