阅读 58

GO语言JSON处理

mysql 查询 数据 json 和反json

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	)
	
	func init() {
	database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/foroo_beta_shopify")
	if err != nil {
		fmt.Println("open mysql failed,",err)
		return
	}
	Db = database
	//defer database.Close()
}
var store []*FrStore
err := Db.Select(&store, "select * from fr_store where id=?", 203189784342958081)
if err != nil {
	fmt.Println("exec failed, ", err)
	return
}
strcc, _ := json.Marshal(store)
fmt.Println(string(strcc))
fmt.Printf("%# v\n", pretty.Formatter(store))
return
lstr := "[{\"id\":203189784342958081,\"store_name\":\"petiopet\",\"cate\":2,\"last_sync_time\":\"2021-01-06T07:18:20+00:00\",\"created_at\":1609404219,\"updated_at\":1609917587,\"version\":2}]\n"
err1 := json.Unmarshal([]byte(lstr),&store)
if err1 != nil {
	fmt.Println("解析失败")
}
fmt.Printf("%# v\n", pretty.Formatter(store))
return	

复制代码

struct 定义

    type Person struct {
        //"-"是忽略的意思
        Name  string `json:"-"`
        Hobby string `json:"hobby" `
    }
复制代码

json 转义

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    student := make(map[string]interface{})
    student["name"] = "5lmh.com"
    student["age"] = 18
    student["sex"] = "man"
    b, err := json.Marshal(student)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(b)
}
复制代码

json 反解析

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Age       int    `json:"age,string"`
    Name      string `json:"name"`
    Niubility bool   `json:"niubility"`
}

func main() {
    // 假数据
    b := []byte(`{"age":"18","name":"5lmh.com","marry":false}`)
    var p Person
    err := json.Unmarshal(b, &p)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(p)
}
复制代码

interface 反转义

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    // 假数据
    // int和float64都当float64
    b := []byte(`{"age":1.3,"name":"5lmh.com","marry":false}`)

    // 声明接口
    var i interface{}
    err := json.Unmarshal(b, &i)
    if err != nil {
        fmt.Println(err)
    }
    // 自动转到map
    fmt.Println(i)
    // 可以判断类型
    m := i.(map[string]interface{})
    for k, v := range m {
        switch vv := v.(type) {
        case float64:
            fmt.Println(k, "是float64类型", vv)
        case string:
            fmt.Println(k, "是string类型", vv)
        default:
            fmt.Println("其他")
        }
    }
}
复制代码

xml 转义和 反转义

    <?xml version="1.0" encoding="UTF-8" ?>
    <servers version="1">
        <server>
            <serverName>Shanghai_VPN</serverName>
            <serverIP>127.0.0.1</serverIP>
        </server>
        <server>
            <serverName>Beijing_VPN</serverName>
            <serverIP>127.0.0.2</serverIP>
        </server>
    </servers>
    
    package main

import (
   "encoding/xml"
   "fmt"
   "io/ioutil"
)

// 抽取单个server对象
type Server struct {
   ServerName string `xml:"serverName"`
   ServerIP   string `xml:"serverIP"`
}

type Servers struct {
   Name    xml.Name `xml:"servers"`
   Version int   `xml:"version"`
   Servers []Server `xml:"server"`
}

func main() {
   data, err := ioutil.ReadFile("D:/my.xml")
   if err != nil {
      fmt.Println(err)
      return
   }
   var servers Servers
   err = xml.Unmarshal(data, &servers)
   if err != nil {
      fmt.Println(err)
      return
   }
   fmt.Printf("xml: %#v\n", servers)
}
复制代码

MSGPack

MSGPack是二进制的json,性能更快,更省空间

go get -u github.com/vmihailenco/msgpack

package main

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

type Person struct {
   Name string
   Age  int
   Sex  string
}

// 二进制写出
func writerJson(filename string) (err error) {
   var persons []*Person
   // 假数据
   for i := 0; i < 10; i++ {
      p := &Person{
         Name: fmt.Sprintf("name%d", i),
         Age:  rand.Intn(100),
         Sex:  "male",
      }
      persons = append(persons, p)
   }
   // 二进制json序列化
   data, err := msgpack.Marshal(persons)
   if err != nil {
      fmt.Println(err)
      return
   }
   err = ioutil.WriteFile(filename, data, 0666)
   if err != nil {
      fmt.Println(err)
      return
   }
   return
}

// 二进制读取
func readJson(filename string) (err error) {
   var persons []*Person
   // 读文件
   data, err := ioutil.ReadFile(filename)
   if err != nil {
      fmt.Println(err)
      return
   }
   // 反序列化
   err = msgpack.Unmarshal(data, &persons)
   if err != nil {
      fmt.Println(err)
      return
   }
   for _, v := range persons {
      fmt.Printf("%#v\n", v)
   }
   return
}

func main() {
   //err := writerJson("D:/person.dat")
   //if err != nil {
   // fmt.Println(err)
   // return
   //}
   err := readJson("D:/person.dat")
   if err != nil {
      fmt.Println(err)
      return
   }
}
复制代码