DEV Community

Khoa Pham
Khoa Pham

Posted on

2 2

How to parse json in Go

Unmarshal using encoding/json

  • property in struct needs to be first letter capitalized
import (
    "net/http"
    "encoding/json"
    "io/ioutil"
    "fmt"
)

type MyJsonObject struct {
    Id string `json:"id"`
    Name string `json:"name"`
}

type MyJsonArray struct {
    Data []MyJsonObject `json:"data"`
}

func FetchJson() {
    url := "https://myapp.com/json"
    client := http.Client{
        Timeout: time.Second * 10
    }

    request, requestError := http.NewRequest(http.MethodGet, url, nil)
    request.Header.Set("User-Agent", "myapp")
    response, responseError := client.Do(request)
    body, readError := ioutil.ReadAll(response.Body)

    fmt.Println(requestError, responseError, readError)

    myJsonArray := MyJsonArray{}
    marshalError := json.Unmarshal(body, &myJsonArray)
    fmt.Println(jsonResponse, marshalError) 
}

Map

And how to map to another struct
https://gobyexample.com/collection-functions

func Map(vs []JsonStop, f func(JsonStop) *api.Stop) []*api.Stop {
    vsm := make([]*api.Stop, len(vs))
    for i, v := range vs {
        vsm[i] = f(v)
    }
    return vsm
}

stops := Map(jsonResponse.Data, func(jsonStop JsonStop) *api.Stop {
        stop := api.Stop{
            Id: jsonStop.Id, 
            Name: jsonStop.Name,
            Address: jsonStop.Address,
            Lat: jsonStop.Lat,
            Long: jsonStop.Long}

        return &stop
    })

Original post https://github.com/onmyway133/blog/issues/199

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs