Adapter to use PyLD's json-ld parser to add triples to librdf.
[htsworkflow.git] / htsworkflow / util / rdfjsonld.py
1 import RDF
2 from pyld import jsonld
3
4 def load_into_model(model, json_data):
5     '''Given a PyLD dictionary, load its statements into our Redland model
6     '''
7     json_graphs = jsonld.to_rdf(json_data)
8     for graph in json_graphs:
9         for triple in json_graphs[graph]:
10             stmt = triple_to_statement(triple)
11             model.add_statement(stmt) #, graph_context)
12
13 def triple_to_statement(triple):
14     '''Convert PyLD triple dictionary to a librdf statement
15     '''
16     s = to_node(triple['subject'])
17     p = to_node(triple['predicate'])
18     o = to_node(triple['object'])
19     return RDF.Statement(s, p, o)
20
21 def to_node(item):
22     '''Convert a PyLD node to a Redland node'''
23     nodetype = item['type']
24     value = item['value']
25     datatype = item.get('datatype', None)
26
27     if nodetype == 'blank node':
28         return RDF.Node(blank=value)
29     elif nodetype == 'IRI':
30         return RDF.Node(uri_string=str(value))
31     else:
32         return RDF.Node(literal=unicode(value).encode('utf-8'),
33                         datatype=RDF.Uri(datatype))