7hacker
7hacker

Reputation: 1978

Create a struct from a byte array

I use the json.Marshal interface to accept a map[string]interface{} and convert it to a []byte (is this a byte array?)

data, _ := json.Marshal(value)
log.Printf("%s\n", data)

I get this output

{"email_address":"[email protected]","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}

The underlying bytes pertain to the struct of the below declaration

type Person struct {
    Name           string  `json:"name"`
    StreetAddress  string  `json:"street_address"`
    Output         string  `json:"output"`
    Status         float64 `json:"status"`
    EmailAddress   string  `json:"email_address",omitempty"`
}

I'd like to take data and generate a variable of type Person struct

How do I do that?

Upvotes: 1

Views: 1113

Answers (1)

LemurFromTheId
LemurFromTheId

Reputation: 4281

You use json.Unmarshal:

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name          string  `json:"name"`
    StreetAddress string  `json:"street_address"`
    Output        string  `json:"output"`
    Status        float64 `json:"status"`
    EmailAddress  string  `json:"email_address",omitempty"`
}

func main() {
    data := []byte(`{"email_address":"[email protected]","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}`)
    var p Person
    if err := json.Unmarshal(data, &p); err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", p)
}

Output:

main.Person{Name:"joe", StreetAddress:"123 Anywhere Anytown", Output:"Hello World", Status:1, EmailAddress:"[email protected]"}

Upvotes: 3

Related Questions