使用go,读取指定文件,并输出到终端

  • json_demo.go
  • package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"io/ioutil"
    	"os"
    )
    
    type v40 struct {
    	V41 int
    	V42 string
    }
    
    type jsonFile struct {
    	V1 string
    	V2 string
    	V3 string
    	v40
    }
    
    func initJsonFile() *jsonFile {
    	var jf jsonFile
    	jf.V1 = "v1"
    	jf.V2 = "v2"
    	jf.V3 = "v3"
    	jf.V41 = 41
    	jf.V42 = "v42"
    	fmt.Println(jf)
    
    	return &jf
    }
    
    func json_test() {
    
    	jf := initJsonFile()
    
    	jsons, err := json.Marshal(*jf)
    
    	if err != nil {
    		fmt.Println(err)
    	}
    
    	fmt.Println(string(jsons))
    
    	var jf2 jsonFile
    	err = json.Unmarshal(jsons, &jf2)
    
    	if err != nil {
    		fmt.Println(err)
    	}
    	fmt.Println(jf2)
    
    }
    
    func jsonReadWrite(path *string) {
    	jsonFile, err := os.Open(*path)
    	if err != nil {
    		fmt.Println(err)
    	}
    	defer jsonFile.Close()
    
    	jsonData, err := ioutil.ReadAll(jsonFile)
    	if err != nil {
    		fmt.Println(err)
    	}
    
    	fmt.Println(string(jsonData))
    
    	var jsonMap map[string]interface{}
    
    	err = json.Unmarshal(jsonData, &jsonMap)
    	if err != nil {
    		fmt.Println(err)
    	}
    	fmt.Println(jsonMap)
    	jsonMap["add"] = "add content"
    	fmt.Println(jsonMap)
    
    	jsonData, err = json.Marshal(jsonMap)
    	if err != nil {
    		fmt.Println(err)
    	}
    	err = ioutil.WriteFile("test_add.json", jsonData, 0555)
    	if err != nil {
    		fmt.Println(err)
    	}
    
    }
    

      

  • main.go
  • package main
    
    import (
    	"flag"
    	"fmt"
    )
    
    func main() {
    	json_test()
    	var path string
    	flag.StringVar(&path, "f", "", "the file path")
    	flag.Parse()
    	fmt.Println(path)
    	a := "./test.json"
    	jsonReadWrite(&a)
    }
    

      

posted @ 2022-08-18 17:08  大长胡子  阅读(85)  评论(0编辑  收藏  举报