Method: JSON::LD::API.flatten

Defined in:
lib/json/ld/api.rb

.flatten(input, context, expanded: false, serializer: nil, **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.

  • expanded (Boolean) (defaults to: false)

    (false) Input is already expanded

  • serializer (Proc) (defaults to: nil)

    (nil) A Serializer instance used for generating the JSON serialization of the result. If absent, the internal Ruby objects are returned, which can be transformed to JSON externally via ‘#to_json`. See serializer.

  • options (Hash{Symbol => Object})

Options Hash (**options):

  • :createAnnotations (Boolean)

    Unfold embedded nodes which can be represented using ‘@annotation`.

  • :adapter (Symbol)

    used with MultiJson

  • :base (RDF::URI, 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 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.

  • :extendedRepresentation (Boolean) — default: false

    Use the extended internal representation.

  • :extractAllScripts (Boolean)

    If set, when given an HTML input without a fragment identifier, extracts all ‘script` elements with type `application/ld+json` into an array during expansion.

  • :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.

  • :language (String)

    When set, this has the effect of inserting a context definition with ‘@language` set to the associated value, creating a default language for interpreting string values.

  • :library (Symbol)

    One of :nokogiri or :rexml. If nil/unspecified uses :nokogiri if available, :rexml otherwise.

  • :lowercaseLanguage (Boolean)

    By default, language tags are left as is. To normalize to lowercase, set this option to ‘true`.

  • :ordered (Boolean) — default: true

    Order traversal of dictionary members by key when performing algorithms.

  • :processingMode (String)

    Processing mode, json-ld-1.0 or json-ld-1.1.

  • :rdfstar (Boolean) — default: false

    support parsing JSON-LD-star statement resources.

  • :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).

  • :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:



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
# File 'lib/json/ld/api.rb', line 290

def self.flatten(input, context, expanded: false, serializer: nil, **options)
  flattened = []
  options = {
    compactToRelative: true,
    extractAllScripts: true
  }.merge(options)

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

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

    # Rename blank nodes recusively. Note that this does not create new blank node identifiers where none exist, which is performed in the node map generation algorithm.
    @value = rename_bnodes(@value) if @options[:rename_bnodes]

    # 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)

    # If create annotations flag is set, then update each node map in graph maps with the result of calling the create annotations algorithm.
    if options[:createAnnotations]
      graph_maps.each_value do |node_map|
        create_annotations(node_map)
      end
    end

    default_graph = graph_maps['@default']
    graph_maps.keys.opt_sort(ordered: @options[:ordered]).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.opt_sort(ordered: @options[:ordered]).each do |id|
        nodes << graph[id] unless node_reference?(graph[id])
      end
    end
    default_graph.keys.opt_sort(ordered: @options[:ordered]).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 = as_array(compact(flattened))
      kwgraph = self.context.compact_iri('@graph', vocab: true)
      flattened = self.context
        .serialize(provided_context: context)
        .merge(kwgraph => compacted)
    end
  end

  flattened = serializer.call(flattened, **options) if serializer
  block_given? ? yield(flattened) : flattened
end