Class: Canon::TreeDiff::Adapters::JSONAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/canon/tree_diff/adapters/json_adapter.rb

Overview

JSONAdapter converts JSON objects to TreeNode structures and back, enabling semantic tree diffing on JSON documents.

This adapter:

  • Converts Hash/Array JSON structures to TreeNode tree

  • Handles nested objects, arrays, and primitive values

  • Preserves type information for round-trip conversion

  • Maps JSON structure to tree representation

JSON to TreeNode mapping:

  • Objects (Hash): TreeNode with label “object”, children for each key

  • Arrays: TreeNode with label “array”, indexed children

  • Primitives: TreeNode with label “value”, value stored directly

Examples:

Convert JSON to TreeNode

json = { "name" => "John", "age" => 30 }
adapter = JSONAdapter.new
tree = adapter.to_tree(json)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(match_options: {}) ⇒ JSONAdapter

Initialize adapter with match options

Parameters:

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

    Match options (for future use)



33
34
35
# File 'lib/canon/tree_diff/adapters/json_adapter.rb', line 33

def initialize(match_options: {})
  @match_options = match_options
end

Instance Attribute Details

#match_optionsObject (readonly)

Returns the value of attribute match_options.



28
29
30
# File 'lib/canon/tree_diff/adapters/json_adapter.rb', line 28

def match_options
  @match_options
end

Instance Method Details

#from_tree(tree_node) ⇒ Hash, ...

Convert TreeNode back to JSON structure

Parameters:

Returns:

  • (Hash, Array, Object)

    JSON structure



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/canon/tree_diff/adapters/json_adapter.rb', line 57

def from_tree(tree_node)
  case tree_node.label
  when "object"
    build_object(tree_node)
  when "array"
    build_array(tree_node)
  when "value"
    parse_value(tree_node)
  else
    # Fallback for custom labels
    tree_node.value
  end
end

#to_tree(data, key = nil) ⇒ Core::TreeNode

Convert JSON structure to TreeNode

Parameters:

  • data (Hash, Array, String, Numeric, Boolean, nil)

    JSON data

  • key (String, nil) (defaults to: nil)

    Key name if this is a hash value

Returns:



42
43
44
45
46
47
48
49
50
51
# File 'lib/canon/tree_diff/adapters/json_adapter.rb', line 42

def to_tree(data, key = nil)
  case data
  when Hash
    convert_object(data, key)
  when Array
    convert_array(data, key)
  else
    convert_value(data, key)
  end
end