Package: easyjsonparser
EasyJSONParser, a lightweight library for parsing and validating your
JSON modelsModern Web frameworks all use ORM systems in order to achieve the
server-side actions on the database: for instance, Doctrine for Symfony3
(PHP), Mongoose for MongoDB databases.ORMs have the ability to read data and convert it into a collections of
in-memory objects. They can also take a special object and convert it
to the underlying storage format.Motivation behind this projectWhile ORM-like systems are pretty common in Web development, they are
inexistant for all other purposes. For instance, parsing a configuration
file (yeah, that's why I designed this library !) and validating its
content, or outputting the configuration in a file.DependenciesEasyJSONParser only uses the Python's standard library, especially thejsonmodule which
serialize and unserialize the source/target data.EasyJSONParser is built for Python 3.InstallationGet the library from Pypi:>pipinstalleasyjsonparserBasic examplesIn this section, we will define dummy data structureUserwhich follows the following schema:{"id":"xxx047AD_","username":"jsonisnice","age":16,"isAdmin":false}EasyJSONParsercan extract parse the data string into an object with the following code:importeasyjsonparserasejpfromeasyjsonparser.documentimportJSONObjectDocumentclassUser(JSONObjectDocument):id=ejp.String()username=ejp.String()age=ejp.Integer()isAdmin=ejp.Boolean()# In this example, the data string is directly# written in the code but it can have# various source such as reading a file...data_string="""..."""user=User.loads(data_string)What if you already have loaded your data into a dictionary ? Then, just useloadinstead ofloads:user=User.load({"id":"xxx047AD_","username":"jsonisnice","age":16,"isAdmin":False})We can get a representation of our user instance by just printing it:>>>print(user)<JSONUserInstance:{"id":<JSONValueStringInstance:"xxx047AD_">,"username":<JSONValueStringInstance:"jsonisnice">,"age":<JSONValueIntegerInstance:16>,"isAdmin":<JSONValueBoolInstance:False>}>What if we now want to parse a list ofUser?fromeasyjsonparser.documentimportJSONAArrayDocumentclassUserList(JSONArrayDocument);schema=User()users=UserList.load([{...},{...}])Document-type objects (ie. the ones that inherit from eitherJSONObjectDocumentorJSONArrayDocument) can be mixed into one another.They also are a variety of types but but the top-level data structure mustalwaysbe either aJSONObjectDocumentorJSONArrayDocument.Well, now what if we want to turn it back to a JSON string ? Let's useto_json()!>>>user.to_json()'{"id": "xxx047AD_", "username": "jsonisnice", "age": 16, "isAdmin": False}'DocumentsDocuments are classes that inherits from eitherJSONObjectDocumentorJSONArrayDocument. They are special kinds ofObjectandArraybecause they contain class methods used for parsing the data. They behave like normalObjectandArraybut have the capacity of being a top-level data structure.The definition of aJSONArrayDocumentis a little bit different than using a regularejp.Array(): the schema must be defined as a class attribute instead of a constructor argument.classStringList(JSONArrayDocument):schema=String()Here are the following special methods:JSONObjectDocument.load(obj=None)(@classmethod)Creates aJSONObjectDocumentwith input sourceobj. If no input is given, then an empty data structure is computed. If an input is given but is not a dictionnary, an exception is raised.JSONObjectDocument.loads(obj_string)(@classmethod)Creates aJSONObjectDocumentfrom a string. The data is parsed to a dictionary usingjson.loads()from Python's standard library. Ifobj_stringdoes not repressent a valid JSON object, an exception is raised.JSONArrayDocument.load(*values)(@classmethod)Creates aJSONArrayDocumentfrom a list of values.valuescan be a variadic array but it is also possible to pass a single input which must be a list or tuple.JSONArrayDocument.loads(array_string)(@classmethod)Creates aJSONArrayDocumentfrom a string. The data is parsed to an array usingjson.loads()from Python's standard library. Ifarray_stringdoes not represent a valid JSON array, an exception is raised.Available typesejp.String()Represents a JSON string.ejp.Integer()Represents a JSON integer.*Warning: boolean and floats are accepted as an input but they will be converted to integers withint(). A warning is raised when a conversion happens.TODO: add an option to disable/enable this behaviourejp.Float()Represents a floating-point number. Conversion from integers and boolean work the way asejp.Integer()ejp.Boolean()Represents a boolean. Conversion from floating-point numbers and boolean work the way asejp.Integer()ejp.Null()Represents anullvalue. Every input that is notNone(in Python) ornull(as a JSON string) will raise a parsing exception.ejp.Object()Represents a JSON object.Properties cannot be defined in the constructor: they must be defined as class attributes as follows:classMyObject(ejp.Object):property1=ejp.String()property2=ejp.Boolean()...Note: remember that you need to useJSONObjectDocumentto define a top-level object.ejp.Array()Represents a JSON array. An array must follow a schema which must be passed to the constructor ofejp.Array(). If the schema is invalid, an exception is raised.classMyObject(ejp.Object):array=ejp.Array(schema=String())Note: remember that you need to useJSONArrayDocumentto define a top-level array.ejp.Empty()Represents an empty value. Used for optional properties/values: if you want to clear the content of an optional parameter, set its value toejp.Empty().LicenseThis software is distributed under theMIT license