LoginSignup
0
0

Golang with JSON

Last updated at Posted at 2023-05-23
  1. Read from Json file and convert to struct

    type Record struct {
    	Time        time.Time
    	Station     string
    	Temperature float64
    	Rain        float64
    }
    
    func readRecord(fileName string) (Record, error) {
    	file, err := os.Open(fileName)
    	if err != nil {
    		log.Fatal(err)
    	}
    	defer file.Close()
    	var rec Record
    	dec := json.NewDecoder(file)
    	if err := dec.Decode(&rec); err != nil {
    		return Record{}, err
    	}
    	return rec, nil
    }
    func main() {
    	fileName := "sample-app/record.json"
    	rec, err := readRecord(fileName)
    	if err != nil {
    		log.Fatal(err)
    	}
    	fmt.Printf("%+v\n", rec)
    }
    
  2. Convert Json string to stuct

    type Student struct {
    	Name string // The name must start with upper case
    	Age  int
    }
    jsonTxt := `[{"name":"tom", "age":13},{"name":"Lily", "age":14}]`
    	var students []Student
    	json.Unmarshal([]byte(jsonTxt), &students)
    	for _, stu := range students {
    		fmt.Printf("%+v", stu)
    	}
    
  3. Convert Map to Json text

func main() {
	states := make(map[string]string)
	states["WA"] = "Washington"
	states["NY"] = "New York"
	states["CA"] = "California"
	jsonText, _ := json.Marshal(states)
	fmt.Println(string(jsonText))
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0