Json Schema Validation in PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
eyals
Forum Newbie
Posts: 3
Joined: Sun Dec 19, 2010 3:45 am

Json Schema Validation in PHP

Post 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? :?:
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Json Schema Validation in PHP

Post by Jonah Bron »

You just want to make sure the format of the object is what you want it to be?
eyals
Forum Newbie
Posts: 3
Joined: Sun Dec 19, 2010 3:45 am

Re: Json Schema Validation in PHP

Post by eyals »

exactly.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Json Schema Validation in PHP

Post 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.
eyals
Forum Newbie
Posts: 3
Joined: Sun Dec 19, 2010 3:45 am

Re: Json Schema Validation in PHP

Post by eyals »

It's more complicated than that.
See the first link I posted here.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Json Schema Validation in PHP

Post 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.
Post Reply