1

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":"joe@me.com","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?

Patryk
  • 22,602
  • 44
  • 128
  • 244
7hacker
  • 1,928
  • 3
  • 19
  • 32

1 Answers1

3

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":"joe@me.com","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:"joe@me.com"}
LemurFromTheId
  • 4,061
  • 1
  • 15
  • 15
  • Awesome! This works! Although I have two follow up questions: This seems a bit roundabout - We first marshal and then unmarshal - is that normal? Is there a way to directly obtain Person struct from map[string]interface{} ? . My second question: lets say email_address field did not exist in data(since its an omitempty field). Do i need to do anything special with the Unmarshal call? Or the above would still work? – 7hacker Mar 13 '16 at 03:39
  • @nthacker, it is somewhat roundabout, but for all I know, there isn't a simple way to convert a map directly into a struct. The real question, however, is where are you getting that map from in the first place? Why is the thing that's producing it not simply giving you a struct? Maybe you could refactor your code so that you don't need a map at all. As for your second question... is there something that prevents your from trying it out yourself? – LemurFromTheId Mar 13 '16 at 04:08
  • you are right on both counts! Thanks I'll look into both of those! – 7hacker Mar 13 '16 at 04:30
  • http://www.gorillatoolkit.org/pkg/schema or https://github.com/mitchellh/mapstructure – elithrar Mar 13 '16 at 05:13