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.JSONPathWildcard
— TypeWildcards 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 aDict
.ANY_INDEX
- Matches any index in aVector
.ANY
- Matches any key or in aDict
or index in aVector
.SKIP_LIST
- If current value in the path is aVector
, matches all indices. If the current value is not aVector
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.
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 list
ERROR: UndefVarError: `data` not defined
julia> data[JSONPath("a2", SKIP_LIST, "b")] # no effect
ERROR: UndefVarError: `data` not defined
julia> data[JSONPath("a1", ANY_INDEX, "b")] # using ANY_INDEX for the same effect
ERROR: 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.StarPattern
— TypeStarPattern 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.
Pattern matching is done using the starmatch
function:
JSONTools.starmatch
— Functionstarmatch(text::String, pattern::StarPattern)
Match the text with a pattern that uses "*" as a wildcard which can represent any number of characters.
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