{"id":18230557,"url":"https://github.com/ashbeelghouri/jsonschematics","last_synced_at":"2026-03-16T08:33:02.581Z","repository":{"id":244216350,"uuid":"809707750","full_name":"ashbeelghouri/jsonschematics","owner":"ashbeelghouri","description":"Validate OR Change the JSON Data With JSON Schema in Golang","archived":false,"fork":false,"pushed_at":"2024-09-27T05:43:38.000Z","size":157,"stargazers_count":3,"open_issues_count":1,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-24T22:24:11.455Z","etag":null,"topics":["arrays","change-data-capture","custom-schematics","error-handling","golang","handlers","json","jsonb","manipulate-data","objects","operations","schema","validation","validators"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ashbeelghouri.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-03T09:46:37.000Z","updated_at":"2024-09-25T11:17:47.000Z","dependencies_parsed_at":"2024-12-21T22:38:32.279Z","dependency_job_id":null,"html_url":"https://github.com/ashbeelghouri/jsonschematics","commit_stats":null,"previous_names":["ashbeelghouri/jsonschematics","ashbeelghouri/go-validate-json"],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashbeelghouri%2Fjsonschematics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashbeelghouri%2Fjsonschematics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashbeelghouri%2Fjsonschematics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashbeelghouri%2Fjsonschematics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ashbeelghouri","download_url":"https://codeload.github.com/ashbeelghouri/jsonschematics/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248323406,"owners_count":21084497,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arrays","change-data-capture","custom-schematics","error-handling","golang","handlers","json","jsonb","manipulate-data","objects","operations","schema","validation","validators"],"created_at":"2024-11-04T11:22:25.483Z","updated_at":"2026-03-16T08:32:57.560Z","avatar_url":"https://github.com/ashbeelghouri.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# jsonschematics\n\n`jsonschematics` is a Go package designed to validate and manipulate JSON data structures using schematics.\n\n## Features\n\n- **Validate JSON objects** against defined schematics\n- **Convert schematics** to JSON schemas\n- **Handle complex data validation** scenarios\n- **Perform operations** on the data\n\n## Installation\n\nTo install the package, use the following command:\n\n```sh\ngo get github.com/ashbeelghouri/jsonschematics@latest\n```\n\n## Usage\n\n### Validation\n\n#### Validating JSON Data\n\nYou can validate JSON data against a defined schematic using the `Validate` function. Here's an example:\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/ashbeelghouri/jsonschematics\"\n)\n\nfunc main() {\n    schema := jsonschematics.Schematics{\n        // Define your schema here\n    }\n\n    data := map[string]interface{}{\n        \"Name\": \"John\",\n        \"Age\":  30,\n    }\n\n    err := schema.Validate(data)\n    if err != nil {\n        fmt.Println(\"Validation errors:\", err)\n    } else {\n        fmt.Println(\"Validation successful\")\n    }\n}\n```\n\n#### Loading Schematics From JSON File\n\nInstead of defining the schema directly, load the schema from a JSON file:\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/ashbeelghouri/jsonschematics\"\n)\n\nfunc main() {\n    var schematics jsonschematics.Schematics\n    err := jsonschematics.LoadSchemaFromFile(\"path-to-your-schema.json\")\n    if err != nil {\n        fmt.Println(\"Unable to load the schema:\", err)\n    } else {\n        fmt.Println(\"Schema Loaded Successfully\")\n    }\n}\n```\n\n#### Loading Schematics From `map[string]interface{}`\n\nIf you want to load the schema from a `map[string]interface{}`, you can use the example below:\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/ashbeelghouri/jsonschematics\"\n)\n\nfunc main() {\n    var schematics jsonschematics.Schematics\n    schema := map[string]interface{}{\n        // Define your schema here\n    }\n\n    err := jsonschematics.LoadSchemaFromMap(\u0026schema)\n    if err != nil {\n        fmt.Println(\"Unable to load the schema:\", err)\n    } else {\n        fmt.Println(\"Schema Loaded Successfully\")\n    }\n}\n```\n\n#### Adding Custom Validation Functions\n\nYou can also add your own functions to validate the data:\n\n##### Example 1\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/ashbeelghouri/jsonschematics\"\n)\n\nfunc main() {\n    var schematics jsonschematics.Schematics\n    err := schematics.LoadSchemaFromFile(\"path-to-your-schema.json\")\n    if err != nil {\n        fmt.Println(\"Unable to load the schema:\", err)\n    }\n    schematics.Validators.RegisterValidator(\"StringIsInsideArr\", StringInArr)\n}\n\nfunc StringInArr(i interface{}, attr map[string]interface{}) error {\n    str := i.(string)\n    strArr := attr[\"arr\"].([]string)\n    found := false\n    if len(strArr) \u003e 0 {\n        for _, item := range strArr {\n            if item == str {\n                found = true\n            }\n        }\n    }\n    if !found {\n        return fmt.Errorf(\"string not found in array\")\n    }\n    return nil\n}\n```\n\n##### Example 2\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/ashbeelghouri/jsonschematics\"\n)\n\nfunc main() {\n    var schematics jsonschematics.Schematics\n    err := schematics.LoadSchemaFromFile(\"path-to-your-schema.json\")\n    if err != nil {\n        fmt.Println(\"Unable to load the schema:\", err)\n    }\n    schematics.Validators.RegisterValidator(\"StringIsInsideArr\", func(i interface{}, attr map[string]interface{}) error {\n        str := i.(string)\n        strArr := attr[\"arr\"].([]interface{})\n        found := false\n        if len(strArr) \u003e 0 {\n            for _, item := range strArr {\n                itemStr := item.(string)\n                if itemStr == str {\n                    found = true\n                }\n            }\n        }\n        if !found {\n            return fmt.Errorf(\"string not found in array\")\n        }\n        return nil\n    })\n}\n```\n\n#### Get Error Messages as a String Slice\n\nYou can get all the error-related information as a slice of strings. For formatting the messages, you can use pre-defined tags that will transform the message into the desired format provided:\n\n- `%message` (error message from the validator)\n- `%target` (name of the field on which validation is performed)\n- `%validator` (name of the validator that is validating the field)\n- `%value` (value on which all the validators are validating)\n\n**Format example:** `validation error %message for %target with validation on %validator, provided: %value`\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/ashbeelghouri/jsonschematics\"\n)\n\nfunc main() {\n    var schematics jsonschematics.Schematics\n    err := jsonschematics.LoadSchemaFromFile(\"path-to-your-schema.json\")\n    if err != nil {\n        fmt.Println(\"String Array of Errors:\", err.ExtractAsStrings(\"%message\"))\n    } else {\n        fmt.Println(\"Schema Loaded Successfully\")\n    }\n}\n```\n\n### Operations\n\n#### Perform Operations on Object\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/ashbeelghouri/jsonschematics\"\n)\n\nfunc main() {\n    schema := jsonschematics.Schematics{\n        // Define your schema here\n    }\n\n    data := map[string]interface{}{\n        \"Name\": \"John\",\n        \"Age\":  30,\n    }\n\n    newData := schema.Operate(data)\n    fmt.Printf(\"Data after Operations: %v\", newData)\n}\n```\n\n#### Adding Custom Operator Functions\n\nYou can also add your own functions to operate on the data:\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"github.com/ashbeelghouri/jsonschematics\"\n)\n\nfunc main() {\n    var schematics jsonschematics.Schematics\n    err := schematics.LoadSchemaFromFile(\"path-to-your-schema.json\")\n    if err != nil {\n        fmt.Println(\"Unable to load the schema:\", err)\n    }\n    schematics.Operators.RegisterOperation(\"CapitalizeString\", Capitalize)\n}\n\nfunc Capitalize(i interface{}, attributes map[string]interface{}) *interface{} {\n    str := i.(string)\n    var opResult interface{} = strings.ToUpper(string(str[0])) + strings.ToLower(str[1:])\n    return \u0026opResult\n}\n```\n\n## API Reference\n\n### Example JSON Files\n\n- [Schema](https://github.com/ashbeelghouri/jsonschematics/blob/master/json/schema.json)\n- [Data](https://github.com/ashbeelghouri/jsonschematics/blob/master/json/data.json)\n\n### Structs\n\n#### Schematics\n\n```go\ntype Schematics struct {\n    Schema                                        Schema\n    Validators                                    Validators\n    Operators                                    Operators\n    Prefix                                        string\n    Separator                                     string\n    ArrayIdKey                                    string\n    LoadSchemaFromFile(path string)                error\n    LoadSchemaFromMap(m *map[string]interface{})   error\n    Validate(data interface{})                     *ErrorMessages\n    Operate(data interface{})                      interface{}\n}\n```\n\n##### Schema\n\n```go\ntype Schema struct {\n    Version string `json:\"version\"`\n    Fields  []Field `json:\"fields\"`\n}\n```\n\n###### Explanation\n\n* `Version` is for the maintenance of the schema\n* `Fields` contains the validation logic for all the keys\n\n##### Field\n\n```go\ntype Field struct {\n    DependsOn   []string  `json:\"depends_on\"`\n    TargetKey   string    `json:\"target_key\"`\n    Description string    `json:\"description\"`\n    Validators  map[string]Constant `json:\"validators\"`\n    Operators   map[string]Constant  `json:\"operators\"`\n}\n```\n\n###### Explanation\n\n* `DependsOn` will check if the keys in the array exist in the data\n* `TargetKey` will target the value in the data through the key\n* `Description` can have anything to explain the data, this can also be empty\n* `Validators` is an array map of validators where the name is the function name and the value contains attributes which is passed along to the function with the value\n* `Operators` is an array map of operators where the name is the function name and the value contains attributes which is passed along to the function with the value\n\n##### Constant\n\n```go\ntype Constant struct {\n    Attributes map[string]interface{} `json:\"attributes\"`\n    ErrMsg      string                `json:\"err\"`\n}\n```\n\n###### Explanation\n\n* `Attributes` are passed into the validation function so it can have any map string interface\n* `ErrMsg` is a string that is shown as an error when validation fails\n\n#### Errors\n\n##### ErrorMessages\n\n```go\ntype ErrorMessages struct {\n    Messages []ErrorMessage\n    AddError(validator string, target string, err string)\n    HaveErrors() bool\n    HaveSingleError(format string) error\n}\n```\n\n##### ErrorMessage\n\n```go\ntype ErrorMessage struct {\n    Message   string\n    Validator string\n    Target    string\n    Value     string\n    ID        string\n}\n```\n\nIf you want to get the single error, you can define the error format like below:\n\"validation error %message for %target on validating with %validator, provided: %value\"\n- `%validator`: this is the name of the validator\n- `%message`: this is the main error message\n- `%target`: this is the target key of the error message\n- `%value`: this is the value on which validation has been performed\n\n###### Explanation\n\n* `Validate` function will always return `ErrorMessages`\n* `Validator` is the function that has validated the value\n* `Target` is the key on which validation has been performed\n* `Value` is the target's value\n* `ID` is the target array key value to identify the validators inside the array, it is very important to define the `arrayKeyID`, so we can identify which row of an array has the validation issues\n\n#### List of Basic Validators\n\n| **String**                  | **Number**       | **Date**         | **Array**                    |\n|-----------------------------|------------------|------------------|------------------------------|\n| IsString                    | IsNumber         | IsValidDate      | ArrayLengthMax               |\n| NotEmpty                    | MaxAllowed       | IsLessThanNow    | ArrayLengthMin               |\n| StringTakenFromOptions      | MinAllowed       | IsMoreThanNow    | StringsTakenFromOptions      |\n| IsEmail                     | InBetween        | IsBefore         |                              |\n| MaxLengthAllowed            |                  | IsAfter          |                              |\n| MinLengthAllowed            |                  | IsInBetweenTime  |                              |\n| InBetweenLengthAllowed      |                  |                  |                              |\n| NoSpecialCharacters         |                  |                  |                              |\n| HaveSpecialCharacters       |                  |                  |                              |\n| LeastOneUpperCase           |                  |                  |                              |\n| LeastOneLowerCase           |                  |                  |                              |\n| LeastOneDigit               |                  |                  |                              |\n| IsURL                       |                  |                  |                              |\n| IsNotURL                    |                  |                  |                              |\n| HaveURLHostName             |                  |                  |                              |\n| HaveQueryParameter          |                  |                  |                              |\n| IsHttps                     |                  |                  |                              |\n| IsURL                       |                  |                  |                              |\n| LIKE                        |                  |                  |                              |\n| MatchRegex                  |                  |                  |                              |\n\n#### Schema\n\n##### v2@latest\nv2 is the lates schema version designed.\nbelow are the required fields listed\n```golang\nfields \u003cARRAY\u003e : [{\n    required \u003cBOOLEAN\u003e\n    depends_on \u003cARRAY OF STRINGS\u003e : [] (can be empty)\n    target_key \u003cSTRING\u003e\n    validators \u003cARRAY OF OBJ\u003e: [{\n        name \u003cSTRING\u003e\n    }]\n    operators \u003cARRAY OF OBJ\u003e: [{\n      \"name\" \u003cSTRING\u003e\n    }],\n}]\n```\n\n###### Target Keys\ntarget key is the key of an array in the data on which operations need to be performed, which can be anything and also can be a regex for the key\nin jsonschematics, we are flattening the object and creating keys with combination of the nested map[string]interface, in result we can get the keys like: map[string]value\nexamples:\n```sh\n- user.profile.name\n- user.*.profile.name (* will be replaced by \\d+)\n```\n\n[**NOTE**] if the string for target is a valid regex then above * conversion wont happen as in regular expressions, the asterisk (*) is a quantifier that means \"zero or more\" of the preceding element\n\n#### Add Custom Data\n- Add the global data inside the schematics right before you are executing the validate function, as it will propogate to the attributes of the function\n- You can add them in the main Schematics Object or add it to the schema file as well as if you want to keep the values from the data use \"add_to_db\" in schema file to add your value to attributes\n\n##### Example 1\nAdding Data in Schematics\n\n```go\nvar s Schematics\nSchematics.DB = map[string]interface{}{\n    \"my-data\":\"valueofthedata\"\n}\n```\n##### Example 2\nAdding data globally in schema\n```json\n{   \"fields\": [...],\n    \"DB\": {\n        \"test\": 22\n      }\n}\n```\n\n##### Example 3\nAdding data from the json that is being validated\n```json\n{   \"fields\": [{\n        \"name\":\"field name\"\n        \"target_key\":\"user.data\",\n        \"add_to_db\": true,\n    }],\n    \"DB\": {\n        \"test\": 22\n      }\n}\n```\n\n**Results** Data will be propogated to the attributes map[string]interface{} like below under \"DB\" key.\n```go\nconstants.Attributes[\"DB\"] = db\n```\n\n#### Go Version\n\n```go\ngo 1.22.1\n```\n\n## Contributing\n\n1. Fork the repository on GitHub.\n2. Create a new branch for your feature or bug fix.\n3. Write tests to cover your changes.\n4. Update the documentation to include your features/changes.\n5. Add yourself to the contributors.\n6. Send a pull request.\n\n### Contributors\n\n\u003ctable style=\"border: none;\"\u003e\n\t\u003ctbody\u003e\n\t\t\u003ctr\u003e\n\t\t\t\u003ctd align=\"center\"\u003e\n                \u003cp\u003e\u003ca href=\"https://github.com/ashbeelghouri\"\u003e\u003cimg src=\"https://github.com/ashbeelghouri.png\" height=\"60px\" width=\"60px\"/\u003e\u003c/a\u003e\u003c/p\u003e\n\t\t\t\t\u003cp\u003e\u003ca href=\"https://github.com/ashbeelghouri\"\u003eAshbeel Ghouri\u003c/a\u003e\u003c/p\u003e\n\t\t\t\u003c/td\u003e\n            \u003ctd align=\"center\"\u003e\n                \u003cp\u003e\u003ca href=\"https://github.com/neddodiallo\"\u003e\u003cimg src=\"https://github.com/neddodiallo.png\" height=\"60px\" width=\"60px\"/\u003e\u003c/a\u003e\u003c/p\u003e\n\t\t\t\t\u003cp\u003e\u003ca href=\"https://github.com/neddodiallo\"\u003eAmadou Diallo\u003c/a\u003e\u003c/p\u003e\n            \u003c/td\u003e\n\t\t\u003c/tr\u003e\n\t\u003c/tbody\u003e\n\u003c/table\u003e\n\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](https://github.com/ashbeelghouri/jsonschematics/blob/master/LICENSE) file for details.\n\n## Future Plans\n\n- Add more built-in validators and operators\n- Improve documentation and examples\n- Support for more complex data structures and validation rules\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fashbeelghouri%2Fjsonschematics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fashbeelghouri%2Fjsonschematics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fashbeelghouri%2Fjsonschematics/lists"}