Go के महत्वपूर्ण विषय
Go JSON: Marshal and Unmarshal
Turn structs into JSON and JSON into structs, with struct tags to choose the field names.
आप क्या सीखेंगे
- json.Marshal
- json.Unmarshal
- Struct tags and omitempty
Round trip
- 1
Product{...}a struct - 2
json.Marshal{"name":"Go Book",...} - 3
json.Unmarshalback to a struct
Structs to JSON and back
The encoding/json package converts Go values to JSON text and JSON text back to Go values. Struct tags choose the names used in the JSON.
Marshal turns the struct into JSON bytes, using the names from the json tags. Unmarshal fills a struct from JSON and needs a pointer so it can change the value. omitempty leaves a field out when it is empty, and a missing field keeps its zero value.
मुख्य बातें
- Tags choose the names used in JSON.
- Unmarshal needs a pointer.
- omitempty leaves out empty fields.
चलने योग्य Go उदाहरण
main.go
package main
import (
"encoding/json"
"fmt"
)
type Product struct {
Name string `json:"name"`
Price float64 `json:"price"`
Tags []string `json:"tags,omitempty"`
}
func main() {
book := Product{Name: "Go Book", Price: 12.5, Tags: []string{"go", "learning"}}
data, err := json.Marshal(book)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(string(data))
var parsed Product
input := `{"name":"Pen","price":1.25}`
if err := json.Unmarshal([]byte(input), &parsed); err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("%s costs %.2f, tags: %d\n", parsed.Name, parsed.Price, len(parsed.Tags))
}
{"name":"Go Book","price":12.5,"tags":["go","learning"]}
Pen costs 1.25, tags: 0अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- JSON ऑब्जेक्ट बनाएँ कुंजियों और मानों को JSON ऑब्जेक्ट स्ट्रिंग में बदलें, कोट और बैकस्लैश को सही ढंग से एस्केप करते हुए। आसान
- सपाट JSON ऑब्जेक्ट का जोड़ ऐसे flat JSON object को parse करें जिनके values integers हैं और values का कुल जोड़ निकालें। आसान