Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

AVRO schema for JSON

I have a JSON which gets generated like this. I wanted to know what would the avro schema for this would be. The number of keys values in array list is not fixed. There are related posts but they have the keys referenced and do not change. In my case the keys change. The names of the variable keys keeps on changing.



"fixedKey": [
                {
                    "variableKey1": 2
                },
                {
                    "variableKey2": 1
                },
                {
                    "variableKey3": 3
                },
                .....
                {
                    "variableKeyN" : 10
                }
    
    
            ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The schema should be something like this:

{
    "type": "record",
    "name": "test",
    "fields": [
        {
            "name": "fixedKey",
            "type": {
                "type": "array",
                "items": [
                    {"type": "map", "values": "int"},
                ],
            },
        }
    ],
}

Here's an example of serializing and deserializing your example data:

from io import BytesIO
from fastavro import writer, reader


schema = {
    "type": "record",
    "name": "test",
    "fields": [
        {
            "name": "fixedKey",
            "type": {
                "type": "array",
                "items": [
                    {"type": "map", "values": "int"},
                ],
            },
        }
    ],
}

records = [
    {
        "fixedKey": [
            {
                "variableKey1": 1,
            },
            {
                "variableKey2": 2,
            },
            {
                "variableKey3": 3,
            },
        ]
    }
]

bio = BytesIO()

writer(bio, schema, records)
bio.seek(0)
for record in reader(bio):
    print(record)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...