Class: JSON::LD::API

Inherits:
Object show all
Includes:
Compact, Expand, Flatten, Frame, FromRDF, ToRDF, RDF::Util::Logger
Defined in:
vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb

Overview

A JSON-LD processor based on the JsonLdProcessor interface.

This API provides a clean mechanism that enables developers to convert JSON-LD data into a a variety of output formats that are easier to work with in various programming languages. If a JSON-LD API is provided in a programming environment, the entirety of the following API must be implemented.

Note that the API method signatures are somewhat different than what is specified, as the use of Futures and explicit callback parameters is not as relevant for Ruby-based interfaces.

Defined Under Namespace

Classes: RemoteDocument

Constant Summary

OPEN_OPTS =

Options used for open_file

{
  headers: {"Accept" => "application/ld+json, application/json"}
}

Instance Attribute Summary collapse

Class Method Summary collapse

Methods included from RDF::Util::Logger

#log_debug, #log_depth, #log_error, #log_fatal, #log_info, #log_recover, #log_recovering?, #log_statistics, #log_warn, #logger

Methods included from Frame

#cleanup_preserve, #count_blank_node_identifiers, #count_blank_node_identifiers_internal, #frame, #remove_dependents

Methods included from Utils

#add_value, #as_resource, #blank_node?, #compare_values, #graph?, #has_property, #has_value, #index?, #list?, #node?, #node_or_ref?, #node_reference?, #simple_graph?, #value?

Methods included from FromRDF

#from_statements

Methods included from Flatten

#create_node_map

Methods included from ToRDF

#item_to_rdf, #node, #parse_list

Methods included from Compact

#compact

Methods included from Expand

#expand

Instance Attribute Details

#contextJSON::LD::Context

Input evaluation context

Returns:



48
49
50
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 48

def context
  @context
end

#inputString, ...

Current input

Returns:



43
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 43

attr_accessor :value

#namerJSON::LD::BlankNodeNamer (readonly)

Current Blank Node Namer



53
54
55
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 53

def namer
  @namer
end

#valueString, ...

Current input

Returns:



43
44
45
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 43

def value
  @value
end

Class Method Details

.compact(input, context, options = {}) {|jsonld| ... } ⇒ Object, Hash

Compacts the given input according to the steps in the Compaction Algorithm. The input must be copied, compacted and returned if there are no errors. If the compaction fails, an appropirate exception must be thrown.

If no context is provided, the input document is compacted using the top-level context of the document

The resulting Hash is either returned or yielded, if a block is given.

Parameters:

Options Hash (options):

  • :expanded (Boolean)

    Input is already expanded

  • :base (String, #to_s)

    The Base IRI to use when expanding the document. This overrides the value of input if it is a IRI. If not specified and input is not an IRI, the base IRI defaults to the current document IRI if in a browser context, or the empty string if there is no document context. If not specified, and a base IRI is found from input, options[:base] will be modified with this value.

  • :compactArrays (Boolean) — default: true

    If set to true, the JSON-LD processor replaces arrays with just one element with that element during compaction. If set to false, all arrays will remain arrays even if they have just one element.

  • :compactToRelative (Boolean) — default: true

    Creates document relative IRIs when compacting, if true, otherwise leaves expanded.

  • :documentLoader (Proc)

    The callback of the loader to be used to retrieve remote documents and contexts. If specified, it must be used to retrieve remote documents and contexts; otherwise, if not specified, the processor's built-in loader must be used. See documentLoader for the method signature.

  • :expandContext (String, #read, Hash, Array, JSON::LD::Context)

    A context that is used to initialize the active context when expanding a document.

  • :flatten (Boolean, String, RDF::URI)

    If set to a value that is not false, the JSON-LD processor must modify the output of the Compaction Algorithm or the Expansion Algorithm by coalescing all properties associated with each subject via the Flattening Algorithm. The value of flatten must be either an IRI value representing the name of the graph to flatten, or true. If the value is true, then the first graph encountered in the input document is selected and flattened.

  • :processingMode (String)

    Processing mode, json-ld-1.0 or json-ld-1.1. Also can have other values:

    • json-ld-1.1-expand-frame – special frame expansion mode.

    If processingMode is not specified, a mode of json-ld-1.0 or json-ld-1.1 is set, the context used for expansion or compaction.

  • :rename_bnodes (Boolean) — default: true

    Rename bnodes as part of expansion, or keep them the same.

  • :unique_bnodes (Boolean) — default: false

    Use unique bnode identifiers, defaults to using the identifier which the node was originally initialized with (if any).

  • :adapter (Symbol)

    used with MultiJson

  • :validate (Boolean)

    Validate input, if a string or readable object.

Yields:

  • jsonld

Yield Parameters:

  • jsonld (Hash)

    The compacted JSON-LD document

Yield Returns:

  • (Object)

    returned object

Returns:

  • (Object, Hash)

    If a block is given, the result of evaluating the block is returned, otherwise, the compacted JSON-LD document

Raises:

See Also:



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
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 218

def self.compact(input, context, options = {})
  result = nil
  options = {compactToRelative:  true}.merge(options)

  # 1) Perform the Expansion Algorithm on the JSON-LD input.
  #    This removes any existing context to allow the given context to be cleanly applied.
  expanded_input = options[:expanded] ? input : API.expand(input, options) do |result, base_iri|
    options[:base] ||= base_iri if options[:compactToRelative]
    result
  end

  API.new(expanded_input, context, options.merge(no_default_base: true)) do
    log_debug(".compact") {"expanded input: #{expanded_input.to_json(JSON_STATE) rescue 'malformed json'}"}
    result = compact(value)

    # xxx) Add the given context to the output
    ctx = self.context.serialize
    if result.is_a?(Array)
      kwgraph = self.context.compact_iri('@graph', vocab: true, quiet: true)
      result = result.empty? ? {} : {kwgraph => result}
    end
    result = ctx.merge(result) unless ctx.empty?
  end
  block_given? ? yield(result) : result
end

.documentLoader(url, options = {}) {|remote_document| ... } ⇒ Object, RemoteDocument

Default document loader.

Parameters:

Options Hash (options):

  • :validate (Boolean)

    Allow only appropriate content types

Yields:

  • remote_document

Yield Parameters:

Yield Returns:

  • (Object)

    returned object

Returns:

  • (Object, RemoteDocument)

    If a block is given, the result of evaluating the block is returned, otherwise, the retrieved remote document and context information unless block given

Raises:



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
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 522

def self.documentLoader(url, options = {})
  options = OPEN_OPTS.merge(options)
  RDF::Util::File.open_file(url, options) do |remote_doc|
    content_type = remote_doc.content_type if remote_doc.respond_to?(:content_type)
    # If the passed input is a DOMString representing the IRI of a remote document, dereference it. If the retrieved document's content type is neither application/json, nor application/ld+json, nor any other media type using a +json suffix as defined in [RFC6839], reject the promise passing an loading document failed error.
    if content_type && options[:validate]
      main, sub = content_type.split("/")
      raise JSON::LD::JsonLdError::LoadingDocumentFailed, "url: #{url}, content_type: #{content_type}" if
        main != 'application' ||
        sub !~ /^(.*\+)?json$/
    end

    # If the input has been retrieved, the response has an HTTP Link Header [RFC5988] using the http://www.w3.org/ns/json-ld#context link relation and a content type of application/json or any media type with a +json suffix as defined in [RFC6839] except application/ld+json, update the active context using the Context Processing algorithm, passing the context referenced in the HTTP Link Header as local context. The HTTP Link Header is ignored for documents served as application/ld+json If multiple HTTP Link Headers using the http://www.w3.org/ns/json-ld#context link relation are found, the promise is rejected with a JsonLdError whose code is set to multiple context link headers and processing is terminated.
    contextUrl = unless content_type.nil? || content_type.start_with?("application/ld+json")
      # Get context link(s)
      # Note, we can't simply use #find_link, as we need to detect multiple
      links = remote_doc.links.links.select do |link|
        link.attr_pairs.include?(%w(rel http://www.w3.org/ns/json-ld#context))
      end
      raise JSON::LD::JsonLdError::MultipleContextLinkHeaders,
        "expected at most 1 Link header with rel=jsonld:context, got #{links.length}" if links.length > 1
      Array(links.first).first
    end

    doc_uri = remote_doc.base_uri rescue url
    doc = RemoteDocument.new(doc_uri, remote_doc.read, contextUrl)
    block_given? ? yield(doc) : doc
  end
rescue IOError => e
  raise JSON::LD::JsonLdError::LoadingDocumentFailed, e.message
end

.expand(input, options = {}) {|jsonld, base_iri| ... } ⇒ Object, Array<Hash>

Expands the given input according to the steps in the Expansion Algorithm. The input must be copied, expanded and returned if there are no errors. If the expansion fails, an appropriate exception must be thrown.

The resulting Array either returned or yielded

Parameters:

Options Hash (options):

  • :base (String, #to_s)

    The Base IRI to use when expanding the document. This overrides the value of input if it is a IRI. If not specified and input is not an IRI, the base IRI defaults to the current document IRI if in a browser context, or the empty string if there is no document context. If not specified, and a base IRI is found from input, options[:base] will be modified with this value.

  • :compactArrays (Boolean) — default: true

    If set to true, the JSON-LD processor replaces arrays with just one element with that element during compaction. If set to false, all arrays will remain arrays even if they have just one element.

  • :compactToRelative (Boolean) — default: true

    Creates document relative IRIs when compacting, if true, otherwise leaves expanded.

  • :documentLoader (Proc)

    The callback of the loader to be used to retrieve remote documents and contexts. If specified, it must be used to retrieve remote documents and contexts; otherwise, if not specified, the processor's built-in loader must be used. See documentLoader for the method signature.

  • :expandContext (String, #read, Hash, Array, JSON::LD::Context)

    A context that is used to initialize the active context when expanding a document.

  • :flatten (Boolean, String, RDF::URI)

    If set to a value that is not false, the JSON-LD processor must modify the output of the Compaction Algorithm or the Expansion Algorithm by coalescing all properties associated with each subject via the Flattening Algorithm. The value of flatten must be either an IRI value representing the name of the graph to flatten, or true. If the value is true, then the first graph encountered in the input document is selected and flattened.

  • :processingMode (String)

    Processing mode, json-ld-1.0 or json-ld-1.1. Also can have other values:

    • json-ld-1.1-expand-frame – special frame expansion mode.

    If processingMode is not specified, a mode of json-ld-1.0 or json-ld-1.1 is set, the context used for expansion or compaction.

  • :rename_bnodes (Boolean) — default: true

    Rename bnodes as part of expansion, or keep them the same.

  • :unique_bnodes (Boolean) — default: false

    Use unique bnode identifiers, defaults to using the identifier which the node was originally initialized with (if any).

  • :adapter (Symbol)

    used with MultiJson

  • :validate (Boolean)

    Validate input, if a string or readable object.

Yields:

  • jsonld, base_iri

Yield Parameters:

  • jsonld (Array<Hash>)

    The expanded JSON-LD document

  • base_iri (RDF::URI)

    The document base as determined during expansion

Yield Returns:

  • (Object)

    returned object

Returns:

  • (Object, Array<Hash>)

    If a block is given, the result of evaluating the block is returned, otherwise, the expanded JSON-LD document

Raises:

See Also:



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
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 169

def self.expand(input, options = {}, &block)
  result, doc_base = nil
  API.new(input, options[:expandContext], options) do
    result = self.expand(self.value, nil, self.context,
      ordered: options.fetch(:ordered, true),
      framing: @options[:processingMode].to_s.include?('expand-frame'))
    doc_base = @options[:base]
  end

  # If, after the algorithm outlined above is run, the resulting element is an JSON object with just a @graph property, element is set to the value of @graph's value.
  result = result['@graph'] if result.is_a?(Hash) && result.length == 1 && result.key?('@graph')

  # Finally, if element is a JSON object, it is wrapped into an array.
  result = [result].compact unless result.is_a?(Array)

  if block_given?
    case block.arity
    when 1 then yield(result)
    when 2 then yield(result, doc_base)
    else
      raise "Unexpected number of yield parameters to expand"
    end
  else
    result
  end
end

.flatten(input, context, options = {}) {|jsonld| ... } ⇒ Object, Hash

This algorithm flattens an expanded JSON-LD document by collecting all properties of a node in a single JSON object and labeling all blank nodes with blank node identifiers. This resulting uniform shape of the document, may drastically simplify the code required to process JSON-LD data in certain applications.

The resulting Array is either returned, or yielded if a block is given.

Parameters:

  • input (String, #read, Hash, Array)

    The JSON-LD object or array of JSON-LD objects to flatten or an IRI referencing the JSON-LD document to flatten.

  • context (String, #read, Hash, Array, JSON::LD::EvaluationContext)

    An optional external context to use additionally to the context embedded in input when expanding the input.

  • options (Hash{Symbol => Object}) (defaults to: {})

Options Hash (options):

  • :expanded (Boolean)

    Input is already expanded

  • :base (String, #to_s)

    The Base IRI to use when expanding the document. This overrides the value of input if it is a IRI. If not specified and input is not an IRI, the base IRI defaults to the current document IRI if in a browser context, or the empty string if there is no document context. If not specified, and a base IRI is found from input, options[:base] will be modified with this value.

  • :compactArrays (Boolean) — default: true

    If set to true, the JSON-LD processor replaces arrays with just one element with that element during compaction. If set to false, all arrays will remain arrays even if they have just one element.

  • :compactToRelative (Boolean) — default: true

    Creates document relative IRIs when compacting, if true, otherwise leaves expanded.

  • :documentLoader (Proc)

    The callback of the loader to be used to retrieve remote documents and contexts. If specified, it must be used to retrieve remote documents and contexts; otherwise, if not specified, the processor's built-in loader must be used. See documentLoader for the method signature.

  • :expandContext (String, #read, Hash, Array, JSON::LD::Context)

    A context that is used to initialize the active context when expanding a document.

  • :flatten (Boolean, String, RDF::URI)

    If set to a value that is not false, the JSON-LD processor must modify the output of the Compaction Algorithm or the Expansion Algorithm by coalescing all properties associated with each subject via the Flattening Algorithm. The value of flatten must be either an IRI value representing the name of the graph to flatten, or true. If the value is true, then the first graph encountered in the input document is selected and flattened.

  • :processingMode (String)

    Processing mode, json-ld-1.0 or json-ld-1.1. Also can have other values:

    • json-ld-1.1-expand-frame – special frame expansion mode.

    If processingMode is not specified, a mode of json-ld-1.0 or json-ld-1.1 is set, the context used for expansion or compaction.

  • :rename_bnodes (Boolean) — default: true

    Rename bnodes as part of expansion, or keep them the same.

  • :unique_bnodes (Boolean) — default: false

    Use unique bnode identifiers, defaults to using the identifier which the node was originally initialized with (if any).

  • :adapter (Symbol)

    used with MultiJson

  • :validate (Boolean)

    Validate input, if a string or readable object.

Yields:

  • jsonld

Yield Parameters:

  • jsonld (Hash)

    The flattened JSON-LD document

Yield Returns:

  • (Object)

    returned object

Returns:

  • (Object, Hash)

    If a block is given, the result of evaluating the block is returned, otherwise, the flattened JSON-LD document

See Also:



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
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 263

def self.flatten(input, context, options = {})
  flattened = []
  options = {compactToRelative:  true}.merge(options)

  # Expand input to simplify processing
  expanded_input = options[:expanded] ? input : API.expand(input, options) do |result, base_iri|
    options[:base] ||= base_iri if options[:compactToRelative]
    result
  end

  # Initialize input using
  API.new(expanded_input, context, options.merge(no_default_base: true)) do
    log_debug(".flatten") {"expanded input: #{value.to_json(JSON_STATE) rescue 'malformed json'}"}

    # Initialize node map to a JSON object consisting of a single member whose key is @default and whose value is an empty JSON object.
    graph_maps = {'@default' => {}}
    create_node_map(value, graph_maps)

    default_graph = graph_maps['@default']
    graph_maps.keys.sort.each do |graph_name|
      next if graph_name == '@default'

      graph = graph_maps[graph_name]
      entry = default_graph[graph_name] ||= {'@id' => graph_name}
      nodes = entry['@graph'] ||= []
      graph.keys.sort.each do |id|
        nodes << graph[id] unless node_reference?(graph[id])
      end
    end
    default_graph.keys.sort.each do |id|
      flattened << default_graph[id] unless node_reference?(default_graph[id])
    end

    if context && !flattened.empty?
      # Otherwise, return the result of compacting flattened according the Compaction algorithm passing context ensuring that the compaction result uses the @graph keyword (or its alias) at the top-level, even if the context is empty or if there is only one element to put in the @graph array. This ensures that the returned document has a deterministic structure.
      compacted = compact(flattened)
      compacted = [compacted] unless compacted.is_a?(Array)
      kwgraph = self.context.compact_iri('@graph', quiet: true)
      flattened = self.context.serialize.merge(kwgraph => compacted)
    end
  end

  block_given? ? yield(flattened) : flattened
end

.frame(input, frame, options = {}) {|jsonld| ... } ⇒ Object, Hash

Frames the given input using the frame according to the steps in the Framing Algorithm. The input is used to build the framed output and is returned if there are no errors. If there are no matches for the frame, null must be returned. Exceptions must be thrown if there are errors.

The resulting Array is either returned, or yielded if a block is given.

Parameters:

  • input (String, #read, Hash, Array)

    The JSON-LD object to copy and perform the framing on.

  • frame (String, #read, Hash, Array)

    The frame to use when re-arranging the data.

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :embed ('@last', '@always', '@never', '@link') — default: '@last'

    a flag specifying that objects should be directly embedded in the output, instead of being referred to by their IRI.

  • :explicit (Boolean) — default: false

    a flag specifying that for properties to be included in the output, they must be explicitly declared in the framing context.

  • :requireAll (Boolean) — default: true

    A flag specifying that all properties present in the input frame must either have a default value or be present in the JSON-LD input for the frame to match.

  • :omitDefault (Boolean) — default: false

    a flag specifying that properties that are missing from the JSON-LD input should be omitted from the output.

  • :expanded (Boolean)

    Input is already expanded

  • :pruneBlankNodeIdentifiers (Boolean) — default: true

    removes blank node identifiers that are only used once.

  • :base (String, #to_s)

    The Base IRI to use when expanding the document. This overrides the value of input if it is a IRI. If not specified and input is not an IRI, the base IRI defaults to the current document IRI if in a browser context, or the empty string if there is no document context. If not specified, and a base IRI is found from input, options[:base] will be modified with this value.

  • :compactArrays (Boolean) — default: true

    If set to true, the JSON-LD processor replaces arrays with just one element with that element during compaction. If set to false, all arrays will remain arrays even if they have just one element.

  • :compactToRelative (Boolean) — default: true

    Creates document relative IRIs when compacting, if true, otherwise leaves expanded.

  • :documentLoader (Proc)

    The callback of the loader to be used to retrieve remote documents and contexts. If specified, it must be used to retrieve remote documents and contexts; otherwise, if not specified, the processor's built-in loader must be used. See documentLoader for the method signature.

  • :expandContext (String, #read, Hash, Array, JSON::LD::Context)

    A context that is used to initialize the active context when expanding a document.

  • :flatten (Boolean, String, RDF::URI)

    If set to a value that is not false, the JSON-LD processor must modify the output of the Compaction Algorithm or the Expansion Algorithm by coalescing all properties associated with each subject via the Flattening Algorithm. The value of flatten must be either an IRI value representing the name of the graph to flatten, or true. If the value is true, then the first graph encountered in the input document is selected and flattened.

  • :processingMode (String)

    Processing mode, json-ld-1.0 or json-ld-1.1. Also can have other values:

    • json-ld-1.1-expand-frame – special frame expansion mode.

    If processingMode is not specified, a mode of json-ld-1.0 or json-ld-1.1 is set, the context used for expansion or compaction.

  • :rename_bnodes (Boolean) — default: true

    Rename bnodes as part of expansion, or keep them the same.

  • :unique_bnodes (Boolean) — default: false

    Use unique bnode identifiers, defaults to using the identifier which the node was originally initialized with (if any).

  • :adapter (Symbol)

    used with MultiJson

  • :validate (Boolean)

    Validate input, if a string or readable object.

Yields:

  • jsonld

Yield Parameters:

  • jsonld (Hash)

    The framed JSON-LD document

Yield Returns:

  • (Object)

    returned object

Returns:

  • (Object, Hash)

    If a block is given, the result of evaluating the block is returned, otherwise, the framed JSON-LD document

Raises:

  • (InvalidFrame)

See Also:



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
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 336

def self.frame(input, frame, options = {})
  result = nil
  options = {
    base:                       (input if input.is_a?(String)),
    compactArrays:              true,
    compactToRelative:          true,
    embed:                      '@last',
    explicit:                   false,
    requireAll:                 true,
    omitDefault:                false,
    pruneBlankNodeIdentifiers:  true,
    documentLoader:             method(:documentLoader)
  }.merge(options)

  framing_state = {
    graphMap:     {},
    graphStack:   [],
    subjectStack: [],
    link:         {},
  }

  # de-reference frame to create the framing object
  frame = case frame
  when Hash then frame.dup
  when IO, StringIO then MultiJson.load(frame.read)
  when String
    remote_doc = options[:documentLoader].call(frame)
    case remote_doc.document
    when String then MultiJson.load(remote_doc.document)
    else remote_doc.document
    end
  end

  # Expand input to simplify processing
  expanded_input = options[:expanded] ? input : API.expand(input, options) do |result, base_iri|
    options[:base] ||= base_iri if options[:compactToRelative]
    result
  end

  # Expand frame to simplify processing
  expanded_frame = API.expand(frame, options.merge(processingMode: "json-ld-1.1-expand-frame"))

  # Initialize input using frame as context
  API.new(expanded_input, nil, options.merge(no_default_base: true)) do
    log_debug(".frame") {"expanded input: #{expanded_input.to_json(JSON_STATE) rescue 'malformed json'}"}
    log_debug(".frame") {"expanded frame: #{expanded_frame.to_json(JSON_STATE) rescue 'malformed json'}"}

    # Get framing nodes from expanded input, replacing Blank Node identifiers as necessary
    create_node_map(value, framing_state[:graphMap], graph: '@default')

    frame_keys = frame.keys.map {|k| context.expand_iri(k, vocab: true, quiet: true)}
    if frame_keys.include?('@graph')
      # If frame contains @graph, it matches the default graph.
      framing_state[:graph] = '@default'
    else
      # If frame does not contain @graph used the merged graph.
      framing_state[:graph] = '@merged'
      framing_state[:link]['@merged'] = {}
      framing_state[:graphMap]['@merged'] = merge_node_map_graphs(framing_state[:graphMap])
    end

    framing_state[:subjects] = framing_state[:graphMap][framing_state[:graph]]

    result = []
    frame(framing_state, framing_state[:subjects].keys.sort, (expanded_frame.first || {}), options.merge(parent: result))

    # Count blank node identifiers used in the document, if pruning
    bnodes_to_clear = if options[:pruneBlankNodeIdentifiers]
      count_blank_node_identifiers(result).collect {|k, v| k if v == 1}.compact
    end

    # Initalize context from frame
    @context = @context.parse(frame['@context'])
    # Compact result
    compacted = compact(result)
    compacted = [compacted] unless compacted.is_a?(Array)

    # Add the given context to the output
    kwgraph = context.compact_iri('@graph', quiet: true)
    result = context.serialize.merge({kwgraph => compacted})
    log_debug(".frame") {"after compact: #{result.to_json(JSON_STATE) rescue 'malformed json'}"}
    result = cleanup_preserve(result, bnodes_to_clear || [])
  end

  block_given? ? yield(result) : result
end

.fromRdf(input, options = {}) {|jsonld| ... } ⇒ Object, Hash Also known as: fromRDF

Take an ordered list of RDF::Statements and turn them into a JSON-LD document.

The resulting Array is either returned or yielded, if a block is given.

Parameters:

Options Hash (options):

  • :useRdfType (Boolean) — default: false

    If set to true, the JSON-LD processor will treat rdf:type like a normal property instead of using @type.

  • :useNativeTypes (Boolean) — default: false

    use native representations

  • :base (String, #to_s)

    The Base IRI to use when expanding the document. This overrides the value of input if it is a IRI. If not specified and input is not an IRI, the base IRI defaults to the current document IRI if in a browser context, or the empty string if there is no document context. If not specified, and a base IRI is found from input, options[:base] will be modified with this value.

  • :compactArrays (Boolean) — default: true

    If set to true, the JSON-LD processor replaces arrays with just one element with that element during compaction. If set to false, all arrays will remain arrays even if they have just one element.

  • :compactToRelative (Boolean) — default: true

    Creates document relative IRIs when compacting, if true, otherwise leaves expanded.

  • :documentLoader (Proc)

    The callback of the loader to be used to retrieve remote documents and contexts. If specified, it must be used to retrieve remote documents and contexts; otherwise, if not specified, the processor's built-in loader must be used. See documentLoader for the method signature.

  • :expandContext (String, #read, Hash, Array, JSON::LD::Context)

    A context that is used to initialize the active context when expanding a document.

  • :flatten (Boolean, String, RDF::URI)

    If set to a value that is not false, the JSON-LD processor must modify the output of the Compaction Algorithm or the Expansion Algorithm by coalescing all properties associated with each subject via the Flattening Algorithm. The value of flatten must be either an IRI value representing the name of the graph to flatten, or true. If the value is true, then the first graph encountered in the input document is selected and flattened.

  • :processingMode (String)

    Processing mode, json-ld-1.0 or json-ld-1.1. Also can have other values:

    • json-ld-1.1-expand-frame – special frame expansion mode.

    If processingMode is not specified, a mode of json-ld-1.0 or json-ld-1.1 is set, the context used for expansion or compaction.

  • :rename_bnodes (Boolean) — default: true

    Rename bnodes as part of expansion, or keep them the same.

  • :unique_bnodes (Boolean) — default: false

    Use unique bnode identifiers, defaults to using the identifier which the node was originally initialized with (if any).

  • :adapter (Symbol)

    used with MultiJson

  • :validate (Boolean)

    Validate input, if a string or readable object.

Yields:

  • jsonld

Yield Parameters:

  • jsonld (Hash)

    The JSON-LD document in expanded form

Yield Returns:

  • (Object)

    returned object

Returns:

  • (Object, Hash)

    If a block is given, the result of evaluating the block is returned, otherwise, the expanded JSON-LD document



498
499
500
501
502
503
504
505
506
507
508
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 498

def self.fromRdf(input, options = {}, &block)
  useRdfType = options.fetch(:useRdfType, false)
  useNativeTypes = options.fetch(:useNativeTypes, false)
  result = nil

  API.new(nil, nil, options) do |api|
    result = api.from_statements(input, useRdfType: useRdfType, useNativeTypes: useNativeTypes)
  end

  block_given? ? yield(result) : result
end

.toRdf(input, options = {}) {|statement| ... } ⇒ RDF::Enumerable Also known as: toRDF

Processes the input according to the RDF Conversion Algorithm, calling the provided callback for each triple generated.

Parameters:

  • input (String, #read, Hash, Array)

    The JSON-LD object to process when outputting statements.

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :produceGeneralizedRdf (Boolean) — default: false

    If true, output will include statements having blank node predicates, otherwise they are dropped.

  • :expanded (Boolean)

    Input is already expanded

  • :base (String, #to_s)

    The Base IRI to use when expanding the document. This overrides the value of input if it is a IRI. If not specified and input is not an IRI, the base IRI defaults to the current document IRI if in a browser context, or the empty string if there is no document context. If not specified, and a base IRI is found from input, options[:base] will be modified with this value.

  • :compactArrays (Boolean) — default: true

    If set to true, the JSON-LD processor replaces arrays with just one element with that element during compaction. If set to false, all arrays will remain arrays even if they have just one element.

  • :compactToRelative (Boolean) — default: true

    Creates document relative IRIs when compacting, if true, otherwise leaves expanded.

  • :documentLoader (Proc)

    The callback of the loader to be used to retrieve remote documents and contexts. If specified, it must be used to retrieve remote documents and contexts; otherwise, if not specified, the processor's built-in loader must be used. See documentLoader for the method signature.

  • :expandContext (String, #read, Hash, Array, JSON::LD::Context)

    A context that is used to initialize the active context when expanding a document.

  • :flatten (Boolean, String, RDF::URI)

    If set to a value that is not false, the JSON-LD processor must modify the output of the Compaction Algorithm or the Expansion Algorithm by coalescing all properties associated with each subject via the Flattening Algorithm. The value of flatten must be either an IRI value representing the name of the graph to flatten, or true. If the value is true, then the first graph encountered in the input document is selected and flattened.

  • :processingMode (String)

    Processing mode, json-ld-1.0 or json-ld-1.1. Also can have other values:

    • json-ld-1.1-expand-frame – special frame expansion mode.

    If processingMode is not specified, a mode of json-ld-1.0 or json-ld-1.1 is set, the context used for expansion or compaction.

  • :rename_bnodes (Boolean) — default: true

    Rename bnodes as part of expansion, or keep them the same.

  • :unique_bnodes (Boolean) — default: false

    Use unique bnode identifiers, defaults to using the identifier which the node was originally initialized with (if any).

  • :adapter (Symbol)

    used with MultiJson

  • :validate (Boolean)

    Validate input, if a string or readable object.

Yields:

  • statement

Yield Parameters:

Returns:

Raises:



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
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/api.rb', line 436

def self.toRdf(input, options = {}, &block)
  unless block_given?
    results = []
    results.extend(RDF::Enumerable)
    self.toRdf(input, options) do |stmt|
      results << stmt
    end
    return results
  end

  # Expand input to simplify processing
  expanded_input = options[:expanded] ? input : API.expand(input, options.merge(ordered: false))

  API.new(expanded_input, nil, options) do
    # 1) Perform the Expansion Algorithm on the JSON-LD input.
    #    This removes any existing context to allow the given context to be cleanly applied.
    log_debug(".toRdf") {"expanded input: #{expanded_input.to_json(JSON_STATE) rescue 'malformed json'}"}

    # Recurse through input
    expanded_input.each do |node|
      item_to_rdf(node) do |statement|
        next if statement.predicate.node? && !options[:produceGeneralizedRdf]

        # Drop results with relative IRIs
        relative = statement.to_a.any? do |r|
          case r
          when RDF::URI
            r.relative?
          when RDF::Literal
            r.has_datatype? && r.datatype.relative?
          else
            false
          end
        end
        if relative
          log_debug(".toRdf") {"drop statement with relative IRIs: #{statement.to_ntriples}"}
          next
        end

        yield statement
      end
    end
  end
end