Validates JSON strings against a schema.
@param string $json
@param string $schemaName Name of the .json file providing the schema (without file extension)
@return ValidationResult
489725
public function validateJson(string $json, string $schemaName): ValidationResult
    {
        $schemaDir = $this->config->get('schema-dir');
        $schemaPath = $this->configDirectoryPath.$schemaDir.'/'.$schemaName.'.json';
        if(!file_exists($schemaPath)){
            throw new FileNotFoundException("File $schemaPath not found");
        }
        
        $schemaJsonString = file_get_contents($schemaPath);
        $decodedJson = json_decode($json);
        if ($decodedJson === false) {
            $schema = json_decode($schemaJsonString);
            // error decoding json
            return (new ValidationResult())
                ->addError(new ValidationError($json,
                        [],
                        [],
                        $schema,
                        "Failed to decode JSON string")
                );
        }
        return $this->dataValidation($decodedJson, $schemaJsonString);
    }
404910
public static function validate($data, string $fileSchema): bool
    {
        /**
         * Throw an \Exception in case if there's no file or is unreadable
         */
        if (!file_exists($fileSchema) || !is_readable($fileSchema)) {
            throw new \Exception("The file {$fileSchema} not exists or is not readable.");
        }

        $jsonSchema = self::decode(file_get_contents($fileSchema));

        self::getValidator()->validate($data, $jsonSchema);

        return self::getValidator()->isValid();
    }
131607
async function validateJSON(someJson, jsonschema) {
          utilsLogger.debug("called validateJSON someJson, jsonschema");
          return studyUtils.jsonschema.validate(someJson, jsonschema);
          // return { valid: true, errors: [] };
        }
886127
public function validate($tables, $json)
    {

        /** @var \LaravelRocket\Generator\Validators\BaseRule[] $tableRules */
        $tableRules = [
            new TableName(),
            new PrimaryKeyName(),
        ];

        /** @var \LaravelRocket\Generator\Validators\BaseRule[] $columnRules */
        $columnRules = [
            new ColumnName(),
            new AvoidLongVarChar(),
            new AvoidDateTime(),
            new GenderWithVarChar(),
        ];

        $success = true;
        $errors  = [];

        foreach ($tables as $table) {
            foreach ($tableRules as $rule) {
                list($ruleSuccess, $ruleErrors) = $rule->validate(['table' => $table]);
                if (!$ruleSuccess) {
                    $success = false;
                }
                $errors = array_merge($errors, $ruleErrors);
            }

            foreach ($table->getColumns() as $column) {
                foreach ($columnRules as $rule) {
                    list($ruleSuccess, $ruleErrors) = $rule->validate(['table' => $table, 'column' => $column]);
                    if (!$ruleSuccess) {
                        $success = false;
                    }
                    $errors = array_merge($errors, $ruleErrors);
                }
            }
        }

        return [$success, $errors];
    }
550882
def json_validate(schema, resp):
    
    # is this an error?
    try:
        json_validate_error(resp)
    except ValidationError:
        if json_is_exception(resp):
            # got a traceback 
            if BLOCKSTACK_TEST:
                log.error('\n{}'.format(resp['traceback']))

            return {'error': 'Blockstack Core encountered an exception. See `traceback` for details', 'traceback': resp['traceback'], 'http_status': 500}

        if 'error' in resp and 'http_status' not in resp:
            # bad error message
            raise 

        # not an error.
        jsonschema.validate(resp, schema)

    return resp
1302625
protected function validateSchema($schema)
    {
        if (!is_string($schema) || trim($schema) == '') {
            throw new Exception\InvalidArgumentException(__METHOD__ . ': Schema name must be a valid string or an empty string detected');
        }

        return $this;
    }
885365
def _validate_json(self, checked_json, schema):
        
        try:
            jsonschema.validate(checked_json, schema)
        except jsonschema.ValidationError as e:
            print("""Failed validating '{0}'
in schema {1}:
{2}
On instance {3}:
{4}""".format(e.validator,
              list(e.relative_schema_path)[:-1], pprint.pformat(e.schema),
              "[%s]" % "][".join(repr(index) for index in e.absolute_path),
              pprint.pformat(e.instance).encode('utf-8')))
            raise JsonValidatorError("Failed validating json by schema")
        except jsonschema.SchemaError as e:
            raise JsonValidatorError('Json-schema error')
1008360
public function validate($data, array $options = [])
    {
        // convert data arrays to stdClass for JsonSchema validator
        $dataObject = json_decode(json_encode($data));
        if ($dataObject === []) {
            $dataObject = new \stdClass();
        }

        if (!in_array(Validation::NO_SCHEMA, $options)) {
            // Validate against JSON schema
            $errors = $this->validateSchema($dataObject);
        }

        if (empty($errors)) {
            // Perform additional checks
            $errors = $this->validateAfterSchema($data, $options);
        }

        return $errors;
    }
451192
function checkSchemaErrors(schemaJSON)
    {

      //check against the proper schema definition
      // var vck = self.validator.validateMultiple(schemaJSON, schemaSpec, true);
       var valCheck = self.validateFunction.apply(self.validator, [schemaJSON, schemaSpec, true]);
       
       //grab all possible errors
       var checkErrors = {length: 0};
       var checkWarnings = {length: 0};

       //if we're valid -- which we almost certainly are -- just keep going
       if(!valCheck.valid)
       {
          //let it be known -- this is a weird error
          self.log("Invalid from v4 JSON schema perspective: ", valCheck[errorKey]);

          checkErrors["root"] = valCheck[errorKey];
          checkErrors.length++;

          //not valid, throw it back
          return checkErrors;
       }


       //make sure we have some properties -- otherwise there is literally no validation/
       //during the move process, this is overridden, but it's a good check nonetheless
       if(!schemaJSON.properties && !schemaJSON.items)
       {
          checkErrors["root"] = "No properties/items defined at root. Schema has no validation without properties!";
          checkErrors.length++;
       }

       //going to need to traverse our schema object
       var tJSON = traverse(schemaJSON);

       tJSON.forEach(function(node)
       {
        //skip the root please
        if(this.isRoot || this.path.join(pathDelim).indexOf('required') != -1)
          return;

        //this should be a warning
        if(!self.requireByDefault && !this.isLeaf && !this.node.required)
        {
            //if you don't have a required object, then you're gonna have a bad time
            //this is a warning
            checkWarnings[this.path.join(pathDelim)] = "warning: if you disable requireByDefault and don't put require arrays, validation will ignore those properties.";
            checkWarnings.length++;

        }
        if(this.key == "properties" && this.node.properties)
        {
           checkErrors[this.path.join(pathDelim)] = "Properties inside properties is meaningless.";
           checkErrors.length++;
        }
        if(this.key == "type" && typeof this.node != "string")
        {
            //for whatever reason, there is a type defined, but not a string in it's place? Waa?
            checkErrors[this.path.join(pathDelim)] = "Types must be string";
            checkErrors.length++;
        }
        if(this.key == "type" && !self.typeRegExp.test(this.node.toLowerCase()))
        {
           checkErrors[this.path.join(pathDelim)] = "Types must be one of " + self.validTypes + " not " + this.node;
           checkErrors.length++;
        }
        if(this.isLeaf)
        {
          //if you don't have a type, and there is no ref object
          if(!this.parent.node.properties && (this.key != "type" && this.key != "$ref") && !this.parent.node.type && !this.parent.node["$ref"])
          {
              checkErrors[this.path.join(pathDelim)] = "Object doesn't have any properties, a valid type, or a reference, therefore it is invalid in the WIN spec.";
              checkErrors.length++;
          }
        }
        //not a leaf, you don't have a reference
        if(!self.allowAnyObjects && !this.isLeaf && !this.node["$ref"] )
        {
          //special case for items -- doesn't apply
          if(this.node.type == "object" && this.key != "items")
          {
            //we're going to check if the list of keys to follow have any non keywords
            //for instance if {type: "object", otherThing: "string"} keys = type, otherThing
            //if instead it's just {type : "object", required : []}, keys = type, required 
            //notice that the top has non-keyword keys, and the bottom example does not 
            //we're looking for the bottom example and rejecting it
            var bHasNonKeywords = hasNonKeywords(this.keys);
            
            //if you ONLY have keywords -- you don't have any other object types
            //you are a violation of win spec and you allow any object or array to be passed in
            if(!bHasNonKeywords){
              // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
              checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'object' type with no inner properties";
              checkErrors.length++;
            }
          }
          else if(this.node.type == "array")
          {
            //if you are an array and you have no items -- not allowed!
            if(!this.node.items){
              // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
              checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'array' type with no inner items";
              checkErrors.length++;
            }
            else
            {
              //if you have a ref -- you're okay for us!
              var bIemsHaveNonKey = this.node.items["$ref"] || this.node.items["type"] || hasNonKeywords(this.node.items.properties || {});
               if(!bIemsHaveNonKey){
                // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
                checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'array' type with no non-keyword inner items";
                checkErrors.length++;
              }
            }
          }
        
        }
        //if you're an array
        if(this.node.type == "array")
        {
          //grab your items
          var items = this.node.items;
          if(!items && !self.allowAnyObjects)
          {
             checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off for arrays, therefore you cannot simple have an 'array' type with no inner items";
              checkErrors.length++;
          }
          else
          {
            items = items || {};
            //we have items -- we shouldn't have a reference type && other items
            if(items.properties && items["$ref"])
            {
              checkErrors[this.path.join(pathDelim)] = "Array items in WIN cannot have properties AND a reference type. One or the other.";
              checkErrors.length++;
            }
          }
        }


       });

       if(checkErrors.length || checkWarnings.length)
        return {errors: checkErrors, warnings: checkWarnings};
      else
        return null;

    }
425363
def validate_config(key: str, config: dict) -> None:
    

    try:
        jsonschema.validate(config, CONFIG_JSON_SCHEMA[key])
    except jsonschema.ValidationError as x_validation:
        raise JSONValidation('JSON validation error on {} configuration: {}'.format(key, x_validation.message))
    except jsonschema.SchemaError as x_schema:
        raise JSONValidation('JSON schema error on {} specification: {}'.format(key, x_schema.message))
250796
private function isValidJsonStructure(string $json): bool
    {
        if ('{' === $json[0] && $json[strlen($json) - 1] !== '}') {
            return false;
        } elseif ('[' === $json[0] && $json[strlen($json) - 1] !== ']') {
            return false;
        } elseif ('{' !== $json[0] && '[' !== $json[0]) {
            return false;
        }

        return true;
    }
902662
protected function checkDisallow($entity, $schema, $entityName)
    {
        if (isset($schema->disallow) && $schema->disallow) {
            $thisSchema = clone $schema;
            $thisSchema->type = $schema->disallow;
            unset($thisSchema->disallow);

            // We are expecting an exception - if one is not thrown,
            // then we have a matching disallowed type
            try {
                $valid = false;
                $this->validateType($entity, $thisSchema, $entityName);
            } catch (ValidationException $e) {
                $valid = true;
            }
            if (!$valid) {
                $disallowedTypes = array_map(function($item){
                    return is_object($item) ? 'object (schema)' : $item;
                }, is_array($schema->disallow) ? $schema->disallow : array($schema->disallow));
                throw new ValidationException(sprintf('Invalid value for [%s], disallowed types are [%s]',
                    $entityName, implode(', ', $disallowedTypes)));
            }
        }

        return $this;
    }
387974
public static function json($json, $name = '...')
    {
        if (!self::isDebug()) {
            return false;
        }

        $jsonData = json_decode($json);
        $result   = self::i()->_jsonEncode($jsonData);

        return self::i()->dump($result, $name);
    }
991363
def get_schema_validator(self, schema_name):
        

        if schema_name not in self.schemas:
            schema_file = self.get_schema_file(schema_name)
            with open(schema_file) as f:
                try:
                    jsn_schema = json.load(f)
                except ValueError as ex:
                    log.error("Could not load %s", schema_file)
                    raise ex

            schemas_folder = self.get_schemas_folder()
            root_schema_path = self.get_schema_path(schemas_folder)
            resolver = jsonschema.RefResolver(root_schema_path, None)
            # cache the schema for future use
            self.schemas[schema_name] = (jsn_schema, resolver)
        else:
            jsn_schema, resolver = self.schemas[schema_name]

        validator = jsonschema.Draft4Validator(schema=jsn_schema, resolver=resolver)
        # validator.check_schema(jsn_schema) # check schema is valid

        return validator
1198510
public static function jsonValidate($jsonString, $asArray)
    {
        $json = json_decode($jsonString, $asArray);

        if (json_last_error() != JSON_ERROR_NONE) {
            throw new InvalidJsonException(json_last_error_msg(), json_last_error());
        }

        return $json;
    }
1255460
public static function validate($form, $errors, $message = '', $style = null) {
		$args = $errors;

		return new JsonView([
			'code'    => self::ERROR,
			'target'  => $form,
			'message' => $message,
			'style'   => $style,
			'args'    => $args,
			'action'  => self::ACT_VALIDATE
		], ['ajax' => '1'], 422);
	}
1029138
def validate(self, data):
        """"""
        try:
            schema_path = os.path.normpath(SCHEMA_ROOT)
            location = u'file://%s' % (schema_path)
            fs_resolver = resolver.LocalRefResolver(location, self.schema)
            jsonschema.Draft3Validator(self.schema, resolver=fs_resolver).validate(data)

        except jsonschema.ValidationError as exc:
            # print "data %s" % (data)
            raise jsonschema.exceptions.ValidationError(str(exc))