Last active
March 27, 2019 16:52
-
-
Save saswata-dutta/49aad56e59730ef371a39e5336a0a3ac to your computer and use it in GitHub Desktop.
get all Field's names from an Avro schema json.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import avro.schema | |
def get_schema_children(avro_schema): | |
children = [] | |
if isinstance(avro_schema, avro.schema.UnionSchema): | |
children = avro_schema.schemas | |
if isinstance(avro_schema, avro.schema.RecordSchema): | |
children = avro_schema.fields | |
if isinstance(avro_schema, avro.schema.Field) and not isinstance(avro_schema.type, avro.schema.PrimitiveSchema): | |
children = get_schema_children(avro_schema.type) | |
return children | |
def get_children_field_names(children, prefix): | |
accum = [] | |
for child in children: | |
accum.extend(get_fields_names(child, prefix)) | |
return accum | |
def get_fields_names(avro_schema, parents = []): | |
accum = [] | |
prefix = parents[:] | |
if 'name' in avro_schema.props: | |
prefix.append(avro_schema.name) | |
accum.append(prefix) | |
children = get_schema_children(avro_schema) | |
children_names = get_children_field_names(children, prefix) | |
accum.extend(children_names) | |
return accum | |
json_str = open('schema1.avsc', "r").read() | |
schema = avro.schema.Parse(json_str) | |
names = list(map(lambda x: '/'.join(x), get_fields_names(schema))) | |
print(names) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"fields": [ | |
{ | |
"name": "house_num", | |
"type": "int" | |
}, | |
{ | |
"name": "street", | |
"type": [ | |
"string", | |
"null" | |
] | |
}, | |
{ | |
"name": "city", | |
"type": "string" | |
} | |
], | |
"name": "Address", | |
"type": "record" | |
}, | |
{ | |
"fields": [ | |
{ | |
"name": "name", | |
"type": "string" | |
}, | |
{ | |
"name": "address", | |
"type": "Address" | |
}, | |
{ | |
"name": "office_address", | |
"type": "Address" | |
}, | |
{ | |
"name": "favorite_number", | |
"type": [ | |
"int", | |
"null" | |
] | |
}, | |
{ | |
"name": "favorite_color", | |
"type": [ | |
"string", | |
"null" | |
] | |
}, | |
{ | |
"name": "phones", | |
"type": { | |
"items": "string", | |
"type": "array" | |
} | |
}, | |
{ | |
"name": "additional", | |
"type": { | |
"type": "map", | |
"values": "string" | |
} | |
} | |
], | |
"name": "User", | |
"type": "record" | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment