Module: Philiprehberger::JsonPath

Defined in:
lib/philiprehberger/json_path.rb,
lib/philiprehberger/json_path/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
'0.3.0'

Class Method Summary collapse

Class Method Details

.count(data, path) ⇒ Integer

Return the number of matches for a JSONPath expression

Parameters:

  • data (Hash, Array)

    the data structure to query

  • path (String)

    JSONPath expression

Returns:

  • (Integer)

    number of matches



42
43
44
# File 'lib/philiprehberger/json_path.rb', line 42

def self.count(data, path)
  query(data, path).size
end

.exists?(data, path) ⇒ Boolean

Check if a JSONPath expression matches anything

Parameters:

  • data (Hash, Array)

    the data structure to query

  • path (String)

    JSONPath expression

Returns:

  • (Boolean)

    true if at least one match exists



51
52
53
# File 'lib/philiprehberger/json_path.rb', line 51

def self.exists?(data, path)
  !query(data, path).empty?
end

.first(data, path) ⇒ Object?

Query data and return the first match

Parameters:

  • data (Hash, Array)

    the data structure to query

  • path (String)

    JSONPath expression

Returns:

  • (Object, nil)

    the first matching value or nil



33
34
35
# File 'lib/philiprehberger/json_path.rb', line 33

def self.first(data, path)
  query(data, path).first
end

.paths(data, path) ⇒ Array<String>

Return the canonical JSONPath strings for every match of an expression

Each returned path is an unambiguous JSONPath that, when re-evaluated, resolves to the single element it identifies. Paths are returned in document order. Returns an empty array when no matches exist.

Parameters:

  • data (Hash, Array)

    the data structure to query

  • path (String)

    JSONPath expression

Returns:

  • (Array<String>)

    canonical JSONPath strings for each match



64
65
66
67
# File 'lib/philiprehberger/json_path.rb', line 64

def self.paths(data, path)
  tokens = tokenize(path)
  evaluate_with_paths(data, tokens).map { |_node, p| p }
end

.query(data, path) ⇒ Array

Query data with a JSONPath expression and return all matches

Parameters:

  • data (Hash, Array)

    the data structure to query

  • path (String)

    JSONPath expression

Returns:

  • (Array)

    all matching values



14
15
16
17
# File 'lib/philiprehberger/json_path.rb', line 14

def self.query(data, path)
  tokens = tokenize(path)
  evaluate(data, tokens)
end

.values(data, path) ⇒ Array

Alias for query (more discoverable name)

Parameters:

  • data (Hash, Array)

    the data structure to query

  • path (String)

    JSONPath expression

Returns:

  • (Array)

    all matching values



24
25
26
# File 'lib/philiprehberger/json_path.rb', line 24

def self.values(data, path)
  query(data, path)
end