How to parse json in Golang?

Member

by vaughn , in category: Golang , 2 years ago

How to parse json in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by rozella , 2 years ago

@vaughn use JSON package and Unmarshal() method to parse any JSON string in Golang, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
   "encoding/json"
   "fmt"
)

type Product struct {
   Name  string `json:"name"`
   Price int    `json:"price"`
}

func main() {
   var product Product

   str := `{"name": "iphone 14", "price": 999}`

   err := json.Unmarshal([]byte(str), &product)

   if err != nil {
      panic(err)
   }

   // Output: iphone 14
   fmt.Println(product.Name)
   // Output: 999
   fmt.Println(product.Price)
}
by reilly_kunze , a year ago

@vaughn