Page 1 of 1

Json Schema Validation in PHP

Posted: Sun Dec 19, 2010 3:50 am
by eyals
I'm looking for a class that checks if a JSON object is valid based on a JSON Schema file, as described here: http://davidwalsh.name/json-validation

I found only this, but it doesn't seem to be active
http://sourceforge.net/projects/jsonschemaphpv/

Any ideas? :?:

Re: Json Schema Validation in PHP

Posted: Sun Dec 19, 2010 4:02 pm
by Jonah Bron
You just want to make sure the format of the object is what you want it to be?

Re: Json Schema Validation in PHP

Posted: Sun Dec 19, 2010 4:50 pm
by eyals
exactly.

Re: Json Schema Validation in PHP

Posted: Sun Dec 19, 2010 5:39 pm
by Jonah Bron
You could do a recursive comparison function like this:

Code: Select all

function validateObject($object, stdClass $pattern) {
    if (!is_object($object) || !($object instanceof stdClass)) {
        return false;
    }
    foreach ($pattern as $key => $property) {
        if (!isset($object->$key)) {
            return false;
        } else {
            if (is_object($property)) {
                return validateObject($object->$key, $property);
            }
        }
        return true;
    }
}
Not tested. Just pass it the object, and an object to compare against.

Re: Json Schema Validation in PHP

Posted: Mon Dec 20, 2010 12:11 am
by eyals
It's more complicated than that.
See the first link I posted here.

Re: Json Schema Validation in PHP

Posted: Mon Dec 20, 2010 12:59 pm
by Jonah Bron
Oh, I see. Hm, sorry, I don't know of any projects that do that. If you find one, please let us know though.