msgpack BSON测试笔记

msgpack、JSON、BSON、protobuf等都可以用于不同应用间数据交换
msgpack据说是解析又快又省空间,准备用,后来发现在golang下支持不好,文件大了后就出错,golang对BSON支持的不错

下面是BSON测试程序,记得要安装mongodb附带的那个BSON包
# bson有些问题,数组会被解码成dict
from bson import BSON

with open('ain.bson', "rb") as data_file:    
    data = list(BSON.decode(data_file.read()).values())
 
print(data)
#!/bin/python3
#-*- coding: utf-8 -*-
import numpy as np

def p(x): print(x)

import bson

din = np.zeros([3,3]).tolist()
obj = {"X":din}
# obj.name = "test"

p(np.zeros([3,3]))
s = bson.dumps(obj)
o = bson.loads(s)

p(o)
下面是msgpack测试程序, Python编码
#!/bin/python3
#-*- coding: utf-8 -*-
import numpy as np

def p(x): print(x)

import msgpack

x = [{"msgpack测试":1}, {"test":1}]
y = msgpack.packb(x)

p(msgpack.unpackb(y))

with open("save.txt", "wb") as file:
    file.write(y)
Golang解码
package main

import (
    "fmt"
    "github.com/vmihailenco/msgpack"
    "io/ioutil"
)

func main() {
    var c interface{}
    bytes, err := ioutil.ReadFile("./save.txt")

    if err != nil {
        panic("ReadFile")
    }
    err = msgpack.Unmarshal(bytes, &c)
    if err != nil {
        p(err)
    } else {
        p(c)
    }
}

func p(arg ...interface{}) {
    for _, v := range arg {
        fmt.Printf("%+v\t", v)
    }
    fmt.Printf("\n")
}


发表于:2017-10-12 16:37:45

原文链接(转载请保留): http://www.multisilicon.com/blog/a24334548.html

友情链接: MICROIC
首页