javascript
嵌套的JSON数据与AVRO文件的相互转换
JSON是一種常用的數據交換格式,很多系統都會使用JSON作為數據接口返回的數據格式,然而,由于JSON數據中包含大量的字段名字,導致空間的嚴重浪費,尤其是數據文件較大的時候,而AVRO是一種更加緊湊的數據序列化系統,占用空間相對較少,更利于數據在網絡當中的傳輸,本文介紹如何使用avro-tools工具對這兩種文件格式進行轉換。
準備轉換工具
 使用的是avro-tools-1.8.1.jar,可到官方網站下載。
準備嵌套的JSON數據
 [
 ? {"product_seris":"S_01","product_name":"iphone7","prices":[{"model":"iphone7","price":5200},{"model":"iphone7 plus","price":5800}]},
 ? {"product_seris":"S_02","product_name":"iphone6","prices":[{"model":"iphone6","price":4600},{"model":"iphone6 plus","price":5200}]}
 ]
 模擬數據,請忽略價格信息。以上內容保存為products.json.
準備schema
 在對JSON數據轉換成AVRO數據時,需要提供AVRO數據的schema,這個schema有些復雜,容易出錯,特別是當JSON記錄中有數組的情況。
{"type": "array",
 ?"items":{
 ? ?"type":"record",
 ? ?"name":"products",
 ? ? ?"fields": [
 ? ? ? ? ?{"name": "product_seris", "type": "string"},
 ? ? ? ? ?{"name": "product_name", "type": "string"},
 ? ? ? ? ?{"name": "prices", "type":
 ? ? ? ? ? ? {"type": "array",
 ? ? ? ? ? ? ? ? "items":{
 ? ? ? ? ? ? ? ? ? ? "type":"record",
 ? ? ? ? ? ? ? ? ? ? "name" : "price",
 ? ? ? ? ? ? ? ? ? ? "fields":[
 ? ? ? ? ? ? ? ? ? ? ? {"name":"model","type":"string"},
 ? ? ? ? ? ? ? ? ? ? ? {"name":"price","type":"float"}
 ? ? ? ? ? ? ? ? ? ? ]}
 ? ? ? ? ? ? ? }
 ? ? ? ? ?}
 ? ? ?]
 ?}
 }
 以上內容保存為products.avsc.
幾點解釋:
類型為array,因為從前面的JSON數據上可以看到,整個JSON數據是一個數組,因此,這里的類型為array,當類型為array時,必須指定items。
由于數組內部是記錄形式,因此,在items里面的type是record,這里必須指定name和fields。
fields里的name必須與JSON數據里的字段名保持一致。
值得注意的是,從前面的JSON數據可以看到,prices信息為數組字段,因此,必須先指定name為prices,而且type是一個對象,并不能單純地指定為array,而是需要在對象里再用一個type來指定array,然后再加上items。
嵌套的JSON數據轉換成AVRO數據
 java -jar avro-tools-1.8.1.jar fromjson products.json --schema-file products.avsc > products.avro
 fromjson表示將JSON轉換成AVRO。
--schema-file 后面跟上AVRO 的schema文件。
>表示重定向輸出到文件products.avro,因為默認的是輸出到控制臺。
AVRO數據轉換成相應的JSON數據
 java -jar avro-tools-1.8.1.jar tojson products.avro
 tojson 表示將AVRO數據轉換成JSON數據。結果默認輸出到控制臺,也可使用重定向輸出到文件。
 轉換結果如下:
[yang@master etl]$ java -jar avro-tools-1.8.1.jar tojson products.avro
 log4j:WARN No appenders could be found for logger (org.apache.hadoop.metrics2.lib.MutableMetricsFactory).
 log4j:WARN Please initialize the log4j system properly.
 log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
 [{"product_seris":"S_01","product_name":"iphone7","prices":[{"model":"iphone7","price":5200.0},{"model":"iphone7 plus","price":5800.0}]},{"product_seris":"S_02","product_name":"iphone6","prices":[{"model":"iphone6","price":4600.0},{"model":"iphone6 plus","price":5200.0}]}]
 參考文獻:?
 [1] https://avro.apache.org/docs/current/spec.html
[2] https://avro.apache.org/docs/current/gettingstartedjava.html
[3] http://grokbase.com/t/avro/user/129hab256y/converting-arbitrary-json-to-avro
[4] http://stackoverflow.com/questions/22443051/avro-tools-json-to-avro-schema-fails-org-apache-avro-schemaparseexception-unde
 ?
總結
以上是生活随笔為你收集整理的嵌套的JSON数据与AVRO文件的相互转换的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 推荐系统常用术语
- 下一篇: Apache Avro
