Skip to content

Commit 1f67d65

Browse files
[mod_ginger_rdf] Make parser more robust against variants of nesting (#738)
1 parent ff03fee commit 1f67d65

1 file changed

Lines changed: 19 additions & 9 deletions

File tree

modules/mod_ginger_rdf/support/ginger_json_ld.erl

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
serialize/1,
77
serialize_to_map/1,
88
deserialize/1,
9+
deserialize/2,
910
open/1,
1011
open_file/1,
1112
compact/1
@@ -238,26 +239,35 @@ compact_predicate(Predicate) ->
238239
%% @doc Deserialize a JSON-LD document into an RDF resource.
239240
-spec deserialize(tuple() | list()) -> #rdf_resource{}.
240241
deserialize(JsonLd) when is_map(JsonLd) ->
241-
Context = maps:get(<<"@context">>, JsonLd, #{}),
242+
deserialize_with_context(undefined, JsonLd, #{});
243+
deserialize(JsonLd) ->
244+
%% Fall back to mochijson {struct, ...} structure
245+
open(JsonLd).
246+
247+
%% Guide the parser; indicate that we are actually looking for a specific id
248+
%% so we don't get confused when we encounter multiple subjects in the jsonld.
249+
deserialize(Id, JsonLd) when is_map(JsonLd) ->
250+
deserialize_with_context(Id, JsonLd, #{}).
251+
252+
deserialize_with_context(Id, JsonLd, Context) ->
253+
LocalContext = maps:get(<<"@context">>, JsonLd, #{}),
254+
TotalContext = maps:merge(Context, LocalContext),
242255
maps:fold(
243256
fun(Key, Value, Acc) ->
244-
deserialize(Key, Value, Acc, Context)
257+
deserialize(Key, Value, Acc, TotalContext)
245258
end,
246-
#rdf_resource{},
259+
#rdf_resource{id = Id},
247260
maps:remove(<<"@context">>, JsonLd)
248-
);
249-
deserialize(JsonLd) ->
250-
%% Fall back to mochijson {struct, ...} structure
251-
open(JsonLd).
261+
).
252262

253263
deserialize(<<"@id">>, Uri, #rdf_resource{} = Acc, _Context) ->
254264
Acc#rdf_resource{id = Uri};
255265
deserialize(Predicate, #{<<"@id">> := Uri}, #rdf_resource{} = Acc, Context) ->
256266
deserialize(Predicate, Uri, Acc, Context);
257-
deserialize(<<"@graph">>, Triples, #rdf_resource{triples = ParentTriples} = Acc, _Context) ->
267+
deserialize(<<"@graph">>, Triples, #rdf_resource{triples = ParentTriples} = Acc, Context) ->
258268
AllTriples = lists:foldl(
259269
fun(#{<<"@id">> := _Subject} = Map, ParentAcc) ->
260-
#rdf_resource{triples = GraphTriples} = deserialize(Map),
270+
#rdf_resource{triples = GraphTriples} = deserialize_with_context(undefined, Map, Context),
261271
lists:merge(GraphTriples, ParentAcc)
262272
end,
263273
ParentTriples,

0 commit comments

Comments
 (0)