JSON Parsing and Regular Expressions
Our team is currently working on this feature. If you experience any bugs, please let us know on our Discord. We appreciate your patience.
When dealing with Web Proofs, the ability to parse JSON data is essential. Similarly, finding specific strings or patterns in the subject or body of an email is crucial for Email Proofs.
To support these needs, we provide helpers for parsing text using regular expressions and extracting data from JSON directly within vlayer Prover
contracts.
JSON Parsing
We provide three functions to extract data from JSON based on the field type:
jsonGetInt
: Extracts an integer value and returnsint256
.jsonGetBool
: Extracts a boolean value and returnsbool
.jsonGetString
: Extracts a string value and returnsstring memory
.
import {Prover} from "vlayer/Prover.sol";
import {WebLib} from "vlayer/WebProof.sol";
contract JSONContainsFieldProof is Prover {
using WebLib for string;
function main(string calldata json) public returns (Proof memory, string memory) {
require(json.jsonGetInt("deep.nested.field") == 42, "deep nested field is not 42");
// If we return the provided JSON back, we will be able to pass it to verifier
// Together with a proof that it contains the field
return (proof(), json);
}
}
In the example above, the function extracts the value of the field deep.nested.field
from the JSON string below and checks if it equals 42
.
{
"deep": {
"nested": {
"field": 42
}
}
}
The functions will revert if the field does not exist or if the value is of the wrong type.
Currently, accessing fields inside arrays is not supported.
Regular Expressions
Regular expressions are a powerful tool for finding patterns in text.
We provide a function to match a regular expression against a string:
matches
checks if a string matches a regular expression and returnstrue
if a match is found.
import {Prover} from "vlayer/Prover.sol";
import {RegexLib} from "vlayer/Regex.sol";
contract RegexMatchProof is Prover {
using RegexLib for string;
function main(string calldata text) public returns (Proof memory, string memory) {
// The regex pattern is passed as a string
require(text.matches("^[a-zA-Z0-9]*$"), "text must be alphanumeric only");
// Return proof and provided text if it matches the pattern
return (proof(), text);
}
}