Dave
Dave

Reputation: 8091

How to create a avro Schema from a python dict

I have a python dict that defines the properties of an avro schema:


schema_dict = {
    'type': 'record',
    'name': 'the_name',
    'fields': [{'name':'id', 'type':'string'}, {'name':'value', 'type':'integer'}]
}

How do I create an instance of an avro.schema.Schema from this?

The examples use avro.schema.parse which assumes that the schema is defined as aJSON format string. I don't have that. I could go through the rigamarole of writing the dict to JSON and parsing it, but is there a more direct way of constructing the schema from this data?

Upvotes: 2

Views: 5610

Answers (3)

Scott
Scott

Reputation: 2074

If you already have it in a dictionary format there a make_avsc_object (which is internally called by parse after it does a json.loads()).

So you would just do the following:

from avro.schema import make_avsc_object
parsed_schema = make_avsc_object(schema_dict)

Upvotes: 5

balderman
balderman

Reputation: 23815

How about

avro.schema.parse(json.dumps(schema_dict))

it should work.

Upvotes: 1

Ari Cooper-Davis
Ari Cooper-Davis

Reputation: 3485

avro.schema.Parse expects a serialized JSON, but doesn't require that it comes from a file. So you just need to serialise your dict, which you can do using json.dumps().

So in your case:

schema_parsed = avro.schema.Parse(json.dumps(schema_dict))

Upvotes: 3

Related Questions