Patterns and Wildcards

There are two ways of accessing multiple JSON paths at once using the JSONTools package - Wildcards and Star patterns.

Wildcards

Wildcards are used in common cases when you want to access multiple values at once.

JSONTools.JSONPathWildcardType

Wildcards are used to match multiple keys or indices in a JSON path at once. There are four types of wildcards:

  • ANY_KEY - Matches any key in a Dict.
  • ANY_INDEX - Matches any index in a Vector.
  • ANY - Matches any key or in a Dict or index in a Vector.
  • SKIP_LIST - If current value in the path is a Vector, matches all indices. If the current value is not a Vector it has no effect except for packing current value into a result Tuple with one element.

The wildcards can only be used for reading data, not for setting it.

source

The SKIP_LIST wildcard might not be obvious at first, so here are some examples:

include("../../src/JSONTools.jl")  # hide
using .JSONTools  # hide
# Setup
import JSON

data = JSON.parse("""
    {
        "a1": [
            {"b": "X"},
            {"b": "Y"},
            {"b": "Z"}
        ],
        "a2": {"b": "A"}
    }""")
nothing # hide
julia> data[JSONPath("a1", SKIP_LIST, "b")]  # enters the listERROR: UndefVarError: `data` not defined
julia> data[JSONPath("a2", SKIP_LIST, "b")] # no effectERROR: UndefVarError: `data` not defined
julia> data[JSONPath("a1", ANY_INDEX, "b")] # using ANY_INDEX for the same effectERROR: UndefVarError: `data` not defined

Star patterns

Starn patterns are like wildcards, but they give you more control over which values you want to access. Star patterns are only used for keys, not for indices.

JSONTools.StarPatternType

StarPattern is a custom string created with the start_str macro. It is used for matching text with a pattern that uses "*" as a wildcard against Strings.

Unlike regular String objects StarPattern strings can be indexed by the character position.

source

Pattern matching is done using the starmatch function:

JSONTools.starmatchFunction
starmatch(text::String, pattern::StarPattern)

Match the text with a pattern that uses "*" as a wildcard which can represent any number of characters.

source

The main use case for star patterns is using them in JSONPath objects, but you can use them anywhere you want:

julia> starmatch("This is a message", star"This*")true
julia> starmatch("This is a message", star"XXX*")false
julia> starmatch("This is a message", star"*is*")true