-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathjsonld.py
4689 lines (3975 loc) · 172 KB
/
jsonld.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Python implementation of JSON-LD processor
This implementation is ported from the JavaScript implementation of
JSON-LD.
.. module:: jsonld
:synopsis: Python implementation of JSON-LD
.. moduleauthor:: Dave Longley
.. moduleauthor:: Mike Johnson
.. moduleauthor:: Tim McNamara <tim.mcnamara@okfn.org>
"""
__copyright__ = 'Copyright (c) 2011-2014 Digital Bazaar, Inc.'
__license__ = 'New BSD license'
__version__ = '0.5.5-dev'
__all__ = [
'compact', 'expand', 'flatten', 'frame', 'from_rdf', 'to_rdf',
'normalize', 'set_document_loader', 'get_document_loader',
'parse_link_header', 'load_document',
'register_rdf_parser', 'unregister_rdf_parser',
'JsonLdProcessor', 'JsonLdError', 'ActiveContextCache']
import copy
import gzip
import hashlib
import io
import json
import os
import posixpath
import re
import socket
import ssl
import string
import sys
import traceback
from collections import deque
from contextlib import closing
from numbers import Integral, Real
try:
from functools import cmp_to_key
except ImportError:
def cmp_to_key(mycmp):
"""
Convert a cmp= function into a key= function
Source: http://hg.python.org/cpython/file/default/Lib/functools.py
"""
class K(object):
__slots__ = ['obj']
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
__hash__ = None
return K
# support python 2
if sys.version_info[0] >= 3:
from urllib.request import build_opener as urllib_build_opener
from urllib.request import HTTPSHandler
import urllib.parse as urllib_parse
from http.client import HTTPSConnection
basestring = str
def cmp(a, b):
return (a > b) - (a < b)
else:
from urllib2 import build_opener as urllib_build_opener
from urllib2 import HTTPSHandler
import urlparse as urllib_parse
from httplib import HTTPSConnection
# XSD constants
XSD_BOOLEAN = 'http://www.w3.org/2001/XMLSchema#boolean'
XSD_DOUBLE = 'http://www.w3.org/2001/XMLSchema#double'
XSD_INTEGER = 'http://www.w3.org/2001/XMLSchema#integer'
XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string'
# RDF constants
RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
RDF_LIST = RDF + 'List'
RDF_FIRST = RDF + 'first'
RDF_REST = RDF + 'rest'
RDF_NIL = RDF + 'nil'
RDF_TYPE = RDF + 'type'
RDF_LANGSTRING = RDF + 'langString'
# JSON-LD keywords
KEYWORDS = [
'@base',
'@context',
'@container',
'@default',
'@embed',
'@explicit',
'@graph',
'@id',
'@index',
'@language',
'@list',
'@omitDefault',
'@preserve',
'@reverse',
'@set',
'@type',
'@value',
'@vocab']
# JSON-LD link header rel
LINK_HEADER_REL = 'http://www.w3.org/ns/json-ld#context'
# Restraints
MAX_CONTEXT_URLS = 10
def compact(input_, ctx, options=None):
"""
Performs JSON-LD compaction.
:param input_: the JSON-LD input to compact.
:param ctx: the JSON-LD context to compact with.
:param [options]: the options to use.
[base] the base IRI to use.
[compactArrays] True to compact arrays to single values when
appropriate, False not to (default: True).
[graph] True to always output a top-level graph (default: False).
[expandContext] a context to expand with.
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the compacted JSON-LD output.
"""
return JsonLdProcessor().compact(input_, ctx, options)
def expand(input_, options=None):
"""
Performs JSON-LD expansion.
:param input_: the JSON-LD input to expand.
:param [options]: the options to use.
[base] the base IRI to use.
[expandContext] a context to expand with.
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the expanded JSON-LD output.
"""
return JsonLdProcessor().expand(input_, options)
def flatten(input_, ctx=None, options=None):
"""
Performs JSON-LD flattening.
:param input_: the JSON-LD input to flatten.
:param ctx: the JSON-LD context to compact with (default: None).
:param [options]: the options to use.
[base] the base IRI to use.
[expandContext] a context to expand with.
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the flattened JSON-LD output.
"""
return JsonLdProcessor().flatten(input_, ctx, options)
def frame(input_, frame, options=None):
"""
Performs JSON-LD framing.
:param input_: the JSON-LD input to frame.
:param frame: the JSON-LD frame to use.
:param [options]: the options to use.
[base] the base IRI to use.
[expandContext] a context to expand with.
[embed] default @embed flag (default: True).
[explicit] default @explicit flag (default: False).
[omitDefault] default @omitDefault flag (default: False).
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the framed JSON-LD output.
"""
return JsonLdProcessor().frame(input_, frame, options)
def normalize(input_, options=None):
"""
Performs JSON-LD normalization.
:param input_: the JSON-LD input to normalize.
:param [options]: the options to use.
[base] the base IRI to use.
[format] the format if output is a string:
'application/nquads' for N-Quads.
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the normalized JSON-LD output.
"""
return JsonLdProcessor().normalize(input_, options)
def from_rdf(input_, options=None):
"""
Converts an RDF dataset to JSON-LD.
:param input_: a serialized string of RDF in a format specified
by the format option or an RDF dataset to convert.
:param [options]: the options to use:
[format] the format if input is a string:
'application/nquads' for N-Quads (default: 'application/nquads').
[useRdfType] True to use rdf:type, False to use @type (default: False).
[useNativeTypes] True to convert XSD types into native types
(boolean, integer, double), False not to (default: True).
:return: the JSON-LD output.
"""
return JsonLdProcessor().from_rdf(input_, options)
def to_rdf(input_, options=None):
"""
Outputs the RDF dataset found in the given JSON-LD object.
:param input_: the JSON-LD input.
:param [options]: the options to use.
[base] the base IRI to use.
[format] the format to use to output a string:
'application/nquads' for N-Quads.
[produceGeneralizedRdf] true to output generalized RDF, false
to produce only standard RDF (default: false).
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the resulting RDF dataset (or a serialization of it).
"""
return JsonLdProcessor().to_rdf(input_, options)
def set_document_loader(load_document):
"""
Sets the default JSON-LD document loader.
:param load_document(url): the document loader to use.
"""
global _default_document_loader
_default_document_loader = load_document
def get_document_loader():
"""
Gets the default JSON-LD document loader.
:return: the default document loader.
"""
return _default_document_loader
def parse_link_header(header):
"""
Parses a link header. The results will be key'd by the value of "rel".
Link: <http://json-ld.org/contexts/person.jsonld>; \
rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json"
Parses as: {
'http://www.w3.org/ns/json-ld#context': {
target: http://json-ld.org/contexts/person.jsonld,
type: 'application/ld+json'
}
}
If there is more than one "rel" with the same IRI, then entries in the
resulting map for that "rel" will be lists.
:param header: the link header to parse.
:return: the parsed result.
"""
rval = {}
# split on unbracketed/unquoted commas
entries = re.findall(r'(?:<[^>]*?>|"[^"]*?"|[^,])+', header)
if not entries:
return rval
r_link_header = r'\s*<([^>]*?)>\s*(?:;\s*(.*))?'
for entry in entries:
match = re.search(r_link_header, entry)
if not match:
continue
match = match.groups()
result = {'target': match[0]}
params = match[1]
r_params = r'(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)'
matches = re.findall(r_params, params)
for match in matches:
result[match[0]] = match[2] if match[1] is None else match[1]
rel = result.get('rel', '')
if isinstance(rval.get(rel), list):
rval[rel].append(result)
elif rel in rval:
rval[rel] = [rval[rel], result]
else:
rval[rel] = result
return rval
def load_document(url):
"""
Retrieves JSON-LD at the given URL.
:param url: the URL to retrieve.
:return: the RemoteDocument.
"""
try:
https_handler = VerifiedHTTPSHandler()
url_opener = urllib_build_opener(https_handler)
url_opener.addheaders = [
('Accept', 'application/ld+json, application/json'),
('Accept-Encoding', 'deflate')]
with closing(url_opener.open(url)) as handle:
if handle.info().get('Content-Encoding') == 'gzip':
buf = io.BytesIO(handle.read())
f = gzip.GzipFile(fileobj=buf, mode='rb')
data = f.read()
else:
data = handle.read()
doc = {
'contextUrl': None,
'documentUrl': url,
'document': data.decode('utf8')
}
doc['documentUrl'] = handle.geturl()
headers = dict(handle.info())
content_type = headers.get('content-type')
link_header = headers.get('link')
if link_header and content_type != 'application/ld+json':
link_header = parse_link_header(link_header).get(
LINK_HEADER_REL)
# only 1 related link header permitted
if isinstance(link_header, list):
raise JsonLdError(
'URL could not be dereferenced, it has more than one '
'associated HTTP Link Header.',
'jsonld.LoadDocumentError',
{'url': url},
code='multiple context link headers')
if link_header:
doc['contextUrl'] = link_header['target']
return doc
except JsonLdError as e:
raise e
except Exception as cause:
raise JsonLdError(
'Could not retrieve a JSON-LD document from the URL.',
'jsonld.LoadDocumentError', code='loading document failed',
cause=cause)
def register_rdf_parser(content_type, parser):
"""
Registers a global RDF parser by content-type, for use with
from_rdf. Global parsers will be used by JsonLdProcessors that
do not register their own parsers.
:param content_type: the content-type for the parser.
:param parser(input): the parser function (takes a string as
a parameter and returns an RDF dataset).
"""
global _rdf_parsers
_rdf_parsers[content_type] = parser
def unregister_rdf_parser(content_type):
"""
Unregisters a global RDF parser by content-type.
:param content_type: the content-type for the parser.
"""
global _rdf_parsers
if content_type in _rdf_parsers:
del _rdf_parsers[content_type]
def prepend_base(base, iri):
"""
Prepends a base IRI to the given relative IRI.
:param base: the base IRI.
:param iri: the relative IRI.
:return: the absolute IRI.
"""
# skip IRI processing
if base is None:
return iri
# already an absolute iri
if _is_absolute_iri(iri):
return iri
# parse IRIs
base = urllib_parse.urlsplit(base)
rel = urllib_parse.urlsplit(iri)
# IRI represents an absolute path
if rel.path.startswith('/'):
path = rel.path
else:
path = base.path
# append relative path to the end of the last directory from base
if rel.path != '':
path = path[0:path.rfind('/') + 1]
if len(path) > 0 and not path.endswith('/'):
path += '/'
path += rel.path
add_slash = path.endswith('/')
# normalize path
path = posixpath.normpath(path)
if not path.endswith('/') and add_slash:
path += '/'
# do not include '.' path for fragments
if path == '.' and rel.fragment != '':
path = ''
return urllib_parse.urlunsplit((
base.scheme,
rel.netloc or base.netloc,
path,
rel.query,
rel.fragment
))
def remove_base(base, iri):
"""
Removes a base IRI from the given absolute IRI.
:param base: the base IRI.
:param iri: the absolute IRI.
:return: the relative IRI if relative to base, otherwise the absolute IRI.
"""
# skip IRI processing
if base is None:
return iri
base = urllib_parse.urlsplit(base)
rel = urllib_parse.urlsplit(iri)
# schemes and network locations don't match, don't alter IRI
if not (base.scheme == rel.scheme and base.netloc == rel.netloc):
return iri
path = posixpath.relpath(rel.path, base.path) if rel.path else ''
path = posixpath.normpath(path)
# workaround a relpath bug in Python 2.6 (http://bugs.python.org/issue5117)
if base.path == '/' and path.startswith('../'):
path = path[3:]
if path == '.' and not rel.path.endswith('/') and not (
rel.query or rel.fragment):
path = posixpath.basename(rel.path)
if rel.path.endswith('/') and not path.endswith('/'):
path += '/'
# adjustments for base that is not a directory
if not base.path.endswith('/'):
if path.startswith('../'):
path = path[3:]
elif path.startswith('./'):
path = path[2:]
elif path.startswith('.'):
path = path[1:]
return urllib_parse.urlunsplit((
'', '', path, rel.query, rel.fragment)) or './'
# The default JSON-LD document loader.
_default_document_loader = load_document
# Registered global RDF parsers hashed by content-type.
_rdf_parsers = {}
class JsonLdProcessor:
"""
A JSON-LD processor.
"""
def __init__(self):
"""
Initialize the JSON-LD processor.
"""
# processor-specific RDF parsers
self.rdf_parsers = None
def compact(self, input_, ctx, options):
"""
Performs JSON-LD compaction.
:param input_: the JSON-LD input to compact.
:param ctx: the context to compact with.
:param options: the options to use.
[base] the base IRI to use.
[compactArrays] True to compact arrays to single values when
appropriate, False not to (default: True).
[graph] True to always output a top-level graph (default: False).
[expandContext] a context to expand with.
[skipExpansion] True to assume the input is expanded and skip
expansion, False not to, (default: False).
[activeCtx] True to also return the active context used.
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the compacted JSON-LD output.
"""
if ctx is None:
raise JsonLdError(
'The compaction context must not be null.',
'jsonld.CompactError', code='invalid local context')
# nothing to compact
if input_ is None:
return None
# set default options
options = options or {}
options.setdefault('base', input_ if _is_string(input_) else '')
options.setdefault('compactArrays', True)
options.setdefault('graph', False)
options.setdefault('skipExpansion', False)
options.setdefault('activeCtx', False)
options.setdefault('documentLoader', _default_document_loader)
if options['skipExpansion']:
expanded = input_
else:
# expand input
try:
expanded = self.expand(input_, options)
except JsonLdError as cause:
raise JsonLdError(
'Could not expand input before compaction.',
'jsonld.CompactError', cause=cause)
# process context
active_ctx = self._get_initial_context(options)
try:
active_ctx = self.process_context(active_ctx, ctx, options)
except JsonLdError as cause:
raise JsonLdError(
'Could not process context before compaction.',
'jsonld.CompactError', cause=cause)
# do compaction
compacted = self._compact(active_ctx, None, expanded, options)
if (options['compactArrays'] and not options['graph'] and
_is_array(compacted)):
# simplify to a single item
if len(compacted) == 1:
compacted = compacted[0]
# simplify to an empty object
elif len(compacted) == 0:
compacted = {}
# always use an array if graph options is on
elif options['graph']:
compacted = JsonLdProcessor.arrayify(compacted)
# follow @context key
if _is_object(ctx) and '@context' in ctx:
ctx = ctx['@context']
# build output context
ctx = copy.deepcopy(ctx)
ctx = JsonLdProcessor.arrayify(ctx)
# remove empty contexts
tmp = ctx
ctx = []
for v in tmp:
if not _is_object(v) or len(v) > 0:
ctx.append(v)
# remove array if only one context
ctx_length = len(ctx)
has_context = (ctx_length > 0)
if ctx_length == 1:
ctx = ctx[0]
# add context and/or @graph
if _is_array(compacted):
# use '@graph' keyword
kwgraph = self._compact_iri(active_ctx, '@graph')
graph = compacted
compacted = {}
if has_context:
compacted['@context'] = ctx
compacted[kwgraph] = graph
elif _is_object(compacted) and has_context:
# reorder keys so @context is first
graph = compacted
compacted = {}
compacted['@context'] = ctx
for k, v in graph.items():
compacted[k] = v
if options['activeCtx']:
return {'compacted': compacted, 'activeCtx': active_ctx}
else:
return compacted
def expand(self, input_, options):
"""
Performs JSON-LD expansion.
:param input_: the JSON-LD input to expand.
:param options: the options to use.
[base] the base IRI to use.
[expandContext] a context to expand with.
[keepFreeFloatingNodes] True to keep free-floating nodes,
False not to (default: False).
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the expanded JSON-LD output.
"""
# set default options
options = options or {}
options.setdefault('keepFreeFloatingNodes', False)
options.setdefault('documentLoader', _default_document_loader)
# if input is a string, attempt to dereference remote document
if _is_string(input_):
remote_doc = options['documentLoader'](input_)
else:
remote_doc = {
'contextUrl': None,
'documentUrl': None,
'document': input_
}
try:
if remote_doc['document'] is None:
raise JsonLdError(
'No remote document found at the given URL.',
'jsonld.NullRemoteDocument')
if _is_string(remote_doc['document']):
remote_doc['document'] = json.loads(remote_doc['document'])
except Exception as cause:
raise JsonLdError(
'Could not retrieve a JSON-LD document from the URL.',
'jsonld.LoadDocumentError',
{'remoteDoc': remote_doc}, code='loading document failed',
cause=cause)
# set default base
options.setdefault('base', remote_doc['documentUrl'] or '')
# build meta-object and retrieve all @context urls
input_ = {
'document': copy.deepcopy(remote_doc['document']),
'remoteContext': {'@context': remote_doc['contextUrl']}
}
if 'expandContext' in options:
expand_context = copy.deepcopy(options['expandContext'])
if _is_object(expand_context) and '@context' in expand_context:
input_['expandContext'] = expand_context
else:
input_['expandContext'] = {'@context': expand_context}
try:
self._retrieve_context_urls(
input_, {}, options['documentLoader'], options['base'])
except Exception as cause:
raise JsonLdError(
'Could not perform JSON-LD expansion.',
'jsonld.ExpandError', cause=cause)
active_ctx = self._get_initial_context(options)
document = input_['document']
remote_context = input_['remoteContext']['@context']
# process optional expandContext
if 'expandContext' in input_:
active_ctx = self.process_context(
active_ctx, input_['expandContext']['@context'], options)
# process remote context from HTTP Link Header
if remote_context is not None:
active_ctx = self.process_context(
active_ctx, remote_context, options)
# do expansion
expanded = self._expand(active_ctx, None, document, options, False)
# optimize away @graph with no other properties
if (_is_object(expanded) and '@graph' in expanded and
len(expanded) == 1):
expanded = expanded['@graph']
elif expanded is None:
expanded = []
# normalize to an array
return JsonLdProcessor.arrayify(expanded)
def flatten(self, input_, ctx, options):
"""
Performs JSON-LD flattening.
:param input_: the JSON-LD input to flatten.
:param ctx: the JSON-LD context to compact with (default: None).
:param options: the options to use.
[base] the base IRI to use.
[expandContext] a context to expand with.
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the flattened JSON-LD output.
"""
options = options or {}
options.setdefault('base', input_ if _is_string(input_) else '')
options.setdefault('documentLoader', _default_document_loader)
try:
# expand input
expanded = self.expand(input_, options)
except Exception as cause:
raise JsonLdError(
'Could not expand input before flattening.',
'jsonld.FlattenError', cause=cause)
# do flattening
flattened = self._flatten(expanded)
if ctx is None:
return flattened
# compact result (force @graph option to true, skip expansion)
options['graph'] = True
options['skipExpansion'] = True
try:
compacted = self.compact(flattened, ctx, options)
except Exception as cause:
raise JsonLdError(
'Could not compact flattened output.',
'jsonld.FlattenError', cause=cause)
return compacted
def frame(self, input_, frame, options):
"""
Performs JSON-LD framing.
:param input_: the JSON-LD object to frame.
:param frame: the JSON-LD frame to use.
:param options: the options to use.
[base] the base IRI to use.
[expandContext] a context to expand with.
[embed] default @embed flag (default: True).
[explicit] default @explicit flag (default: False).
[omitDefault] default @omitDefault flag (default: False).
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the framed JSON-LD output.
"""
# set default options
options = options or {}
options.setdefault('base', input_ if _is_string(input_) else '')
options.setdefault('compactArrays', True)
options.setdefault('embed', True)
options.setdefault('explicit', False)
options.setdefault('omitDefault', False)
options.setdefault('documentLoader', _default_document_loader)
# if frame is a string, attempt to dereference remote document
if _is_string(frame):
remote_frame = options['documentLoader'](frame)
else:
remote_frame = {
'contextUrl': None,
'documentUrl': None,
'document': frame
}
try:
if remote_frame['document'] is None:
raise JsonLdError(
'No remote document found at the given URL.',
'jsonld.NullRemoteDocument')
if _is_string(remote_frame['document']):
remote_frame['document'] = json.loads(remote_frame['document'])
except Exception as cause:
raise JsonLdError(
'Could not retrieve a JSON-LD document from the URL.',
'jsonld.LoadDocumentError',
{'remoteDoc': remote_frame}, code='loading document failed',
cause=cause)
# preserve frame context
frame = remote_frame['document']
if frame is not None:
ctx = frame.get('@context', {})
if remote_frame['contextUrl'] is not None:
if ctx:
ctx = JsonLdProcessor.arrayify(ctx)
ctx.append(remote_frame['contextUrl'])
else:
ctx = remote_frame['contextUrl']
frame['@context'] = ctx
try:
# expand input
expanded = self.expand(input_, options)
except JsonLdError as cause:
raise JsonLdError(
'Could not expand input before framing.',
'jsonld.FrameError', cause=cause)
try:
# expand frame
opts = copy.deepcopy(options)
opts['keepFreeFloatingNodes'] = True
expanded_frame = self.expand(frame, opts)
except JsonLdError as cause:
raise JsonLdError(
'Could not expand frame before framing.',
'jsonld.FrameError', cause=cause)
# do framing
framed = self._frame(expanded, expanded_frame, options)
try:
# compact result (force @graph option to True)
options['graph'] = True
options['skipExpansion'] = True
options['activeCtx'] = True
result = self.compact(framed, ctx, options)
except JsonLdError as cause:
raise JsonLdError(
'Could not compact framed output.',
'jsonld.FrameError', cause=cause)
compacted = result['compacted']
active_ctx = result['activeCtx']
# get graph alias
graph = self._compact_iri(active_ctx, '@graph')
# remove @preserve from results
compacted[graph] = self._remove_preserve(
active_ctx, compacted[graph], options)
return compacted
def normalize(self, input_, options):
"""
Performs RDF normalization on the given JSON-LD input.
:param input_: the JSON-LD input to normalize.
:param options: the options to use.
[base] the base IRI to use.
[format] the format if output is a string:
'application/nquads' for N-Quads.
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the normalized output.
"""
# set default options
options = options or {}
options.setdefault('base', input_ if _is_string(input_) else '')
options.setdefault('documentLoader', _default_document_loader)
try:
# convert to RDF dataset then do normalization
opts = copy.deepcopy(options)
if 'format' in opts:
del opts['format']
opts['produceGeneralizedRdf'] = False
dataset = self.to_rdf(input_, opts)
except JsonLdError as cause:
raise JsonLdError(
'Could not convert input to RDF dataset before normalization.',
'jsonld.NormalizeError', cause=cause)
# do normalization
return self._normalize(dataset, options)
def from_rdf(self, dataset, options):
"""
Converts an RDF dataset to JSON-LD.
:param dataset: a serialized string of RDF in a format specified by
the format option or an RDF dataset to convert.
:param options: the options to use.
[format] the format if input is a string:
'application/nquads' for N-Quads (default: 'application/nquads').
[useRdfType] True to use rdf:type, False to use @type
(default: False).
[useNativeTypes] True to convert XSD types into native types
(boolean, integer, double), False not to (default: False).
:return: the JSON-LD output.
"""
global _rdf_parsers
# set default options
options = options or {}
options.setdefault('useRdfType', False)
options.setdefault('useNativeTypes', False)
if ('format' not in options) and _is_string(dataset):
options['format'] = 'application/nquads'
# handle special format
if 'format' in options:
# supported formats (processor-specific and global)
if ((self.rdf_parsers is not None and
not options['format'] in self.rdf_parsers) or
(self.rdf_parsers is None and
not options['format'] in _rdf_parsers)):
raise JsonLdError(
'Unknown input format.',
'jsonld.UnknownFormat', {'format': options['format']})
if self.rdf_parsers is not None:
parser = self.rdf_parsers[options['format']]
else:
parser = _rdf_parsers[options['format']]
dataset = parser(dataset)
# convert from RDF
return self._from_rdf(dataset, options)
def to_rdf(self, input_, options):
"""
Outputs the RDF dataset found in the given JSON-LD object.
:param input_: the JSON-LD input.
:param options: the options to use.
[base] the base IRI to use.
[format] the format if input is a string:
'application/nquads' for N-Quads.
[produceGeneralizedRdf] true to output generalized RDF, false
to produce only standard RDF (default: false).
[documentLoader(url)] the document loader
(default: _default_document_loader).
:return: the resulting RDF dataset (or a serialization of it).
"""
# set default options
options = options or {}
options.setdefault('base', input_ if _is_string(input_) else '')
options.setdefault('produceGeneralizedRdf', False)
options.setdefault('documentLoader', _default_document_loader)
try:
# expand input
expanded = self.expand(input_, options)
except JsonLdError as cause:
raise JsonLdError(
'Could not expand input before serialization to '
'RDF.', 'jsonld.RdfError', cause=cause)
# create node map for default graph (and any named graphs)
namer = UniqueNamer('_:b')
node_map = {'@default': {}}
self._create_node_map(expanded, node_map, '@default', namer)
# output RDF dataset
dataset = {}