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