AlgoMan
AlgoMan

Reputation: 2935

RDF/XML format to JSON

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 ?

Upvotes: 4

Views: 3718

Answers (2)

Brendan Quinn
Brendan Quinn

Reputation: 2249

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')

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881805

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)

Upvotes: 9

Related Questions