4

I am trying to generate a new class in Python starting from a JSON Schema previously defined and created. Then I would like to use the autogenerated class to read a JSON file. My problem is that I manage to create the class from the schema using "python_jsonschema_objects" or "marshmallow_jsonschema" but then when I create an object belonging to that class python do not suggest the elements inside of that class. (I would like to type object.name, and I would like "name" to be suggested by python because it understands that name is a property of object). Moreover the class that these tools create is in the first case an "abc.class" and in the second "class 'marshmallow.schema.GeneratedSchema'". I leave a code example here:

from marshmallow import Schema, fields, post_load

from marshmallow_jsonschema import JSONSchema

from pprint import pprint

import json

class User(object):
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f'I am {self.name} and my age is {self.age}'

   
class UserSchema(Schema):

    name = fields.String()
    age = fields.Integer()

    @post_load
    def make(self, data):
        return User(data)

schema = UserSchema()
json_schema = JSONSchema()

print(json_schema.dump(schema))

with open(abs_path + "schema_test_file.json" , 'w') as outfile:

    json.dump(json_schema.dump(schema), outfile)

with open(abs_path + "schema_test_file.json" ) as json_file:

    data = json.load(json_file)


schema = UserSchema().from_dict(data) **class 'marshmallow.schema.GeneratedSchema'**

user = schema()
user.name = "Marco" **I would like here that python suggest name and age as properties of schema**
user.age = 14

I hope I have been clear enough.

Zaba96
  • 41
  • 2
  • What do you mean by "python suggest name and age as properties of schema"? How would `python` "suggest" anything? – Roland Smith Jan 23 '22 at 08:21
  • So are you trying to create a class object, or a json schema from a class def? It’s very confusing what is the end goal is in this case. – rv.kvetch Jan 23 '22 at 13:06
  • Sorry guys, I was not clear, the general thing I would like to do is to generate a python class from a JSON Schema, but the tool I tried (marshmallow and python-jsonschema-objects) generate a "class 'marshmallow.schema.GeneratedSchema'" and a "class 'abc." which I don't know how to use. – Zaba96 Jan 24 '22 at 09:12
  • I have a similar goal, although, in my case, using a pyspark dataframe vs pandas to read a specific json file returns a "corrupt record column" exception. It does so because some of the nested levels include null dictionaries inside of a list which also happens to be nested. The spark.read(schema).json(file) could serialized if the json had a class processing the shape/structure. I bumped you up a vote. Your approach shows original thnking. – jamiel22 Jan 06 '23 at 13:12

0 Answers0