RDF/XML format to JSON

Question:

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 By: AlgoMan

||

Answers:

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)
Answered By: Alex Martelli

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')
Answered By: Brendan Quinn
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.