JSON schema validation

前端 未结 5 1639
迷失自我
迷失自我 2021-01-30 14:28

Is there a stable library that can validate JSON against a schema?

json-schema.org provides a list of implementations. Notably C and C++ are missing.

Is there a

5条回答
  •  爱一瞬间的悲伤
    2021-01-30 14:59

    Valijson is a very good library which depends only on Boost (And I'm actually hoping to change that). It doesn't even depend on any particular JSON parser, providing adapters for most commonly-used libraries like JsonCpp, rapidjson and json11.

    The code may seem verbose, but you can always write a helper (example for JsonCpp):

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    void validate_json(Json::Value const& root, std::string const& schema_str)
    {
      using valijson::Schema;
      using valijson::SchemaParser;
      using valijson::Validator;
      using valijson::ValidationResults;
      using valijson::adapters::JsonCppAdapter;
    
      Json::Value schema_js;
      {
        Json::Reader reader;
        std::stringstream schema_stream(schema_str);
        if (!reader.parse(schema_stream, schema_js, false))
          throw std::runtime_error("Unable to parse the embedded schema: "
                                   + reader.getFormatedErrorMessages());
      }
    
      JsonCppAdapter doc(root);
      JsonCppAdapter schema_doc(schema_js);
    
      SchemaParser parser(SchemaParser::kDraft4);
      Schema schema;
      parser.populateSchema(schema_doc, schema);
      Validator validator(schema);
      validator.setStrict(false);
      ValidationResults results;
      if (!validator.validate(doc, &results))
      {
        std::stringstream err_oss;
        err_oss << "Validation failed." << std::endl;
        ValidationResults::Error error;
        int error_num = 1;
        while (results.popError(error))
        {
          std::string context;
          std::vector::iterator itr = error.context.begin();
          for (; itr != error.context.end(); itr++)
            context += *itr;
    
          err_oss << "Error #" << error_num << std::endl
                  << "  context: " << context << std::endl
                  << "  desc:    " << error.description << std::endl;
          ++error_num;
        }
        throw std::runtime_error(err_oss.str());
      }
    }
    

提交回复
热议问题