← Back to Go Course | Chapter 14: Standard Library & HTTP | Lesson 6 of 10

encoding/json से JSON Encoding

encoding/json structs (Go के अपने data shapes) और JSON text, अलग-अलग programs के बीच data भेजने के लिए उपयोग होने वाला common format, के बीच Go का translator है।
Syntax
go
data, err := json.Marshal(value)
err := json.Unmarshal(data, &target)

Marshaling a Struct to JSON

json.Marshal किसी Go value -- सबसे आम तौर पर एक struct -- को इसके JSON representation में एक byte slice के रूप में convert करता है, key के रूप में हर exported field का नाम (या इसका json tag, अगर मौजूद हो) उपयोग करते हुए।

उदाहरण: Marshaling a Struct to JSON

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"encoding/json"
	"fmt"
)

// Define a struct type named Book
type Book struct {
	Title  string `json:"title"`
	Pages  int    `json:"pages"`
}

// main is where the program starts running
func main() {
	// Short declaration: create b and infer the type
	b := Book{Title: "Learning Go", Pages: 320}
	// Short declaration: create data, err and infer the type
	data, err := json.Marshal(b)
	// Handle the error if one occurred
	if err != nil {
		// Print the values followed by a newline
		fmt.Println("error:", err)
		return
	}
	fmt.Println(string(data))
}

Unmarshaling JSON into a Struct

json.Unmarshal JSON-encoded bytes को एक Go value में parse करता है, जिसे एक pointer के रूप में पास करना चाहिए ताकि function decoded data को सीधे इसमें लिख सके।

Note: Unmarshal को हमेशा एक pointer पास करें, जैसे &b, ताकि यह असल में fields populate कर सके।

उदाहरण: Unmarshaling JSON into a Struct

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"encoding/json"
	"fmt"
)

// Define a struct type named Book
type Book struct {
	Title string `json:"title"`
	Pages int    `json:"pages"`
}

// main is where the program starts running
func main() {
	// Short declaration: create data and infer the type
	data := []byte(`{"title":"Go in Action","pages":300}`)
	// Declare b with the zero value of its type
	var b Book
	// Run this block only if the condition is true
	if err := json.Unmarshal(data, &b); err != nil {
		// Print the values followed by a newline
		fmt.Println("error:", err)
		return
	}
	fmt.Println(b.Title, b.Pages)
}

Pretty-Printing JSON

json.MarshalIndent Marshal जैसा काम करता है लेकिन हर nested level में एक prefix और indentation जोड़ता है, एक compact line के बजाय human-readable, formatted JSON produce करते हुए।

उदाहरण: Pretty-Printing JSON

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"encoding/json"
	"fmt"
)

// Define a struct type named Config
type Config struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}

// main is where the program starts running
func main() {
	// Short declaration: create c and infer the type
	c := Config{Host: "localhost", Port: 8080}
	// Short declaration: create data, _ and infer the type
	data, _ := json.MarshalIndent(c, "", "  ")
	// Print the values followed by a newline
	fmt.Println(string(data))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि struct fields को json.Marshal को दिखाई देने के लिए exported (capitalized) होना चाहिए -- unexported fields चुपचाप skip हो जाती हैं।
  2. json.Unmarshal को एक non-pointer पास करना, जो target को असल में populate करने में fail होता है क्योंकि इसे जगह पर modify करना चाहिए।
  3. Marshal/Unmarshal से returned error को नज़रअंदाज़ करना, malformed input पर चुपचाप incomplete या zero-valued data के साथ आगे बढ़ते हुए।
चैप्टर सारांश
  • json.Marshal किसी Go value को इसके JSON-encoded byte representation में convert करता है।
  • json.Unmarshal JSON bytes को एक Go value में parse करता है, जिसे एक pointer के रूप में पास करना चाहिए।
  • सिर्फ exported struct fields encoding/json को दिखाई देते हैं; struct tags JSON key names control करते हैं।
  • json.MarshalIndent readability के लिए pretty-printed, indented JSON output produce करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.