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

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay