networknt / json-schema-validator

A fast Java JSON schema validator that supports draft V4, V6, V7, V2019-09 and V2020-12
Apache License 2.0
836 stars 324 forks source link

How to handle loading of relative refs #1055

Closed MoBaT closed 3 months ago

MoBaT commented 3 months ago

Hey! Currently I have json_schema which defines "ref" variables which point to other schema files from a top level directory. For example:

"$ref": "/core/subdir/my_ref"

However, sometimes I define refs that are "relative" paths. This means I have a "schema" file that lives in the folder /core/subdir that defines refs as:

"$ref": "my_ref"

Currently my loader functions looks like:

static void loader(const json_uri &uri, json &schema)
{
    std::string filename = "/home/my_schema/src";
    std::ifstream lf(filename);

    if(!lf.good()) {
        throw std::invalid_argument("could not open " + uri.url() + " tried with " + filename);
    }

    try {
        lf >> schema;
    } catch (const std::exception &e) {
        throw e;
    }

}

However, what I really need is a loader function that can resolve these "relative refs" based on the folder it lives in and to check if it exists or not. Is there a way to easily implement all of this using this library?

justin-tay commented 3 months ago

This is a Java library and not a C++ library.

If you want to understand how refs are supposed to be resolved you can see https://json-schema.org/understanding-json-schema/structuring#dollarref.

You actually need to first convert a relative-iri to an absolute-iri using a base-iri indicated by $id or if missing by its retrieval-iri. This absolute-iri is actually just an identifier and doesn't necessarily map to a retrieval-iri.

MoBaT commented 3 months ago

@justin-tay I'm so dumb.... That makes complete sense! Thanks for helping me out. Sorry about posting in the wrong forum, I sometimes accidentally pull the JAVA github page VS the c++ one and didn't double check to make sure it was the correct place.