golang json format achieved using modified search deletions

Needs and ideas

In general small projects or a small piece of software, such as applets client like, you may need persistent data, but the use of unsuitable general database (Mysql) and the like. This embedded using sqlite3 is a better way, but in the library sqlite3 Go language is C language, Cgo does not support cross-platform compiler. it is because of this demand, it is conceivable to use json format data directly saved in a file.
specific ideas is how ? in the Go language if you want data into json format, there are two formats struct and map. If you need both additions and deletions to change search function, it will map as an intermediate format is more appropriate. then we have to achieve it .

Query operation

This operation is relatively simple to achieve directly read out the data file, using the library json deserialization code can be as follows:

type Product struct {
    Name string `json:"name"`
    Num  int    `json:"num"`
}

func findAll() {
    ps := make([]Product, 0)

    data, err := ioutil.ReadFile("./index.json")
    if err != nil {
        log.Fatal(err)
    }

    // 这里参数要指定为变量的地址
    err = json.Unmarshal(data, &ps)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(ps)
}

Add operation

Add achieved on the basis of reality query, we need to query the database file, and converted into map format, and then struct also converted into map format (to be used here reflex), the combined map, json serialization, last saved in file code is as follows:

func create() {
    fields := make([]map[string]interface{}, 0)
    
    p1 := &Product{
        Name: "Blog",
        Num:  2,
    }
    
    _, _ = json.Marshal(p1)
    // 读取文件中的数据,保存为map格式
    data, _ := ioutil.ReadFile("./index.json")
    err := json.Unmarshal(data, &fields)
    if err != nil {
        log.Fatal(err)
    }
    
    // 使用反射将struct转化为map
    tp := reflect.TypeOf(p1).Elem()
    vp := reflect.ValueOf(p1).Elem()
    field := make(map[string]interface{}, 0)
    for i := 0; i < tp.NumField(); i++ {
        field1 := tp.Field(i)
        field2 := vp.Field(i)
        key := field1.Tag.Get("json")
        field[key] = field2.Interface()
    }
    // 合并map
    fields = append(fields, field)
    
    // 写入文件
    out, _ := json.Marshal(fields)
    _ = ioutil.WriteFile("./index.json", out, 0755)
}

Guess you like

Origin www.cnblogs.com/xingyys/p/11314651.html