W3Basic Logo

Go JSON

Golang has built-in support for JSON (JavaScript Object Notation) through the encoding/json package. The package provides functions for encoding and decoding JSON data and handling errors that may occur during the process.

To encode a Go struct as JSON, you can use the json.Marshal() function, and to decode JSON data into a Go struct, you can use the json.Unmarshal() function.


Encoding JSON in Go:

This example uses the json.Marshal() function to convert a struct to a JSON-encoded byte slice. The json.Marshal() function takes an interface{} as an argument, so you can pass it any value that you want to encode as JSON.

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "John", Age: 30}

    b, err := json.Marshal(p)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(string(b))
}

Output

{"Name":"John","Age":30}

Decoding JSON in Go:

This example uses the json.Unmarshal() function to convert a JSON-encoded byte slice to a struct. The json.Unmarshal() function takes a byte slice and a pointer to a struct as arguments.

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    b := []byte(`{"Name":"John","Age":30}`)

    var p Person
    err := json.Unmarshal(b, &p)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(p)
}

Output

{John 30}

Reading JSON from a file:

This example uses the ioutil.ReadFile() function to read the contents of a file into a byte slice. It then uses the json.Unmarshal() function to convert the byte slice to a struct.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    b, err := ioutil.ReadFile("person.json")
    if err != nil {
        fmt.Println(err)
        return
    }

    var p Person
    err = json.Unmarshal(b, &p)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(p)
}

Output

{John 30}

Writing JSON to a file:

This example uses the json.Marshal() function to convert a struct to a JSON-encoded byte slice. It then uses the ioutil.WriteFile() function to write the contents into a file.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "John", Age: 30}

    b, err := json.Marshal(p)
    if err != nil {
        fmt.Println(err)
        return
    }

    err = ioutil.WriteFile("person.json", b, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }
}

Reading the JSON from the HTTP

This example uses the http.Get() function to make a GET request to a specified URL. The response from the server is stored in the resp variable. It then uses the ioutil.ReadAll() function to read the entire contents of the response body into a byte slice. It then uses the json.Unmarshal() function to convert the byte slice to a struct.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    resp, err := http.Get("https://example.com/person.json")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    b, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    var p Person
    err = json.Unmarshal(b, &p)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(p)
}

Output

{John 30}

Conclusion

In conclusion, Go provides built-in support for encoding and decoding JSON through the encoding/json package. The json.Marshal() function encodes a struct or other value as a JSON-encoded byte slice, while the json.Unmarshal() function is used to decode a JSON-encoded byte slice into a struct or other value.

Additionally, You can read and write JSON data from and to a file using the io/ioutil package's ioutil.ReadFile() and ioutil.WriteFile() functions. And also, you can read a JSON from an HTTP response using net/http package's http.Get() function and ioutil.ReadAll().

© 2023 W3Basic. All rights reserved.

Follow Us: