diff --git a/lib/pyld/jsonld.py b/lib/pyld/jsonld.py index ae27b9cc..fc3b8d4c 100755 --- a/lib/pyld/jsonld.py +++ b/lib/pyld/jsonld.py @@ -768,6 +768,8 @@ def expand(self, input_, options): options = options or {} options.setdefault('keepFreeFloatingNodes', False) options.setdefault('documentLoader', _default_document_loader) + options.setdefault('strict', False) + options.setdefault('droppedKeys', None) # if input is a string, attempt to dereference remote document if _is_string(input_): @@ -1966,6 +1968,7 @@ def _expand( active_ctx, active_property, vocab=True) rval = {} + droppedKeys = options['droppedKeys'] for key, value in sorted(element.items()): if key == '@context': continue @@ -1979,6 +1982,10 @@ def _expand( not ( _is_absolute_iri(expanded_property) or _is_keyword(expanded_property))): + if options['strict']: + raise ValueError("Unrecognized key %s" % key) + elif droppedKeys is not None: + droppedKeys.add(key) continue if _is_keyword(expanded_property): diff --git a/tests/test-issue50.py b/tests/test-issue50.py new file mode 100644 index 00000000..5aed1ade --- /dev/null +++ b/tests/test-issue50.py @@ -0,0 +1,54 @@ +import unittest + +import pyld.jsonld as jsonld + +class TestIssue50(unittest.TestCase): + + CTX = { "foo": { "@id": "http://example.com/foo" } } + DATA = { "fooo": "bar" } + RESULT = [] + + def test_silently_ignored(self): + got = jsonld.expand(self.DATA, + {'expandContext': self.CTX}) + self.assertEqual(got, self.RESULT) + + def test_strict_fails(self): + with self.assertRaises(ValueError): + got = jsonld.expand(self.DATA, + {'expandContext': self.CTX, 'strict': True}) + + def test_dropped_keys(self): + dk = set() + got = jsonld.expand(self.DATA, + {'expandContext': self.CTX, 'droppedKeys': dk}) + self.assertEqual(got, self.RESULT) + self.assertSetEqual(dk, {"fooo"}) + + + DATA2 = { "@id": "foo", "foo": "bar", "fooo": "baz", "http://example.com/other": "blah" } + RESULT2 = [{ "@id": u"foo", + "http://example.com/foo": [{"@value": "bar"}], + "http://example.com/other": [{"@value": "blah"}], + }] + + def test_silently_ignored_2(self): + got = jsonld.expand(self.DATA2, + {'expandContext': self.CTX}) + self.assertEqual(got, self.RESULT2) + + def test_strict_fails_2(self): + with self.assertRaises(ValueError): + got = jsonld.expand(self.DATA2, + {'expandContext': self.CTX, 'strict': True}) + + def test_dropped_keys_2(self): + dk = set() + got = jsonld.expand(self.DATA2, + {'expandContext': self.CTX, 'droppedKeys': dk}) + self.assertEqual(got, self.RESULT2) + self.assertSetEqual(dk, {"fooo"}) + + +if __name__ == "__main__": + unittest.main()