Go and JSON

Parsing into a Struct

Here’s an example of parsing into a struct:

type App struct {
    Id string `json:"id"`
    Title string `json:"title"`
}

data := []byte(`
    {
        "id": "k34rAT4",
        "title": "My Awesome App"
    }
`)

var app App
err := json.Unmarshal(data, &app)

What you’re left with is app populated with the parsed JSON that was in data. You’ll also notice that the go term for parsing json is “Unmarshalling”.

Rendering from a Struct

Outputting from a struct works exactly as parsing but in reverse:

data, err := json.Marshal(app)

As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller.

 

 

You can get rid of the JsonType as well and just use a slice:

package main

import (
    "encoding/json"
    "log"
)

func main() {
    dataJson := `["1","2","3"]`
    var arr []string
    _ = json.Unmarshal([]byte(dataJson), &arr)
    log.Printf("Unmarshaled: %v", arr)
}

// prints out:
// 2009/11/10 23:00:00 Unmarshaled: [1 2 3]

Code on play: https://play.golang.org/p/GNWlylavam

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Можно использовать следующие HTML-теги и атрибуты: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>