Parsing Json in Golang

Concept:

[]Json array ---->[]Byte array ----> Struct


Syntax: func Unmarshal(data []byte, v interface{}) error


Code:

// Golang program to illustrate the

// concept of parsing JSON to an array

package main

import (
    "encoding/json"
    "fmt"
)

// declaring a struct
type Competitors struct {

    // defining struct variables
    Username string
    School   string
    Online   bool
    Score    int
}

// main function
func main() {

    // defining a struct instance
    var competitors []Competitors

    // JSON array to be decoded
    // to an array in golang
    Data := []byte(`
    [
        {"username": "competitor1", "school": "SMK Swasta 1", "online": true, "score": 987},
        {"username": "competitor2", "school": "SMK Negeri 7", "online": false, "score": 432},
        {"username": "competitor3", "school": "SMK Swasta 2", "online": false, "score": 321},
        {"username": "competitor4", "school": "SMK Negeri 10", "online": true, "score": 654}
    ]`)

    // decoding JSON array to
    // the country array
    err := json.Unmarshal(Data, &competitors)

    if err != nil {

        // if error is not nil
        // print error
        fmt.Println(err)
    }

    // printing decoded array
    // values one by one
    for i := range competitors {
        fmt.Printf("%s - %s - %t - %d \n",
            competitors[i].Username, competitors[i].School, competitors[i].Online, competitors[i].Score)
    }
}




Komentar

soal mengatakan…
remot Remote Access VPN dimana tempat nya kawan
soal mengatakan…
Remote Access VPN bisa di kasih panduan nya kawan

Postingan populer dari blog ini

Pembahasan IT Network Systems Administration Module A DNS (Forward Zone, Reverse Zone, CNAME, MX, Split View)

Cara memahami dan menghafal model OSI dengan analogi

Table of Contents