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":"[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?

1 Answer 1

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":"[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]"}
Sign up to request clarification or add additional context in comments.

4 Comments

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?
@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?
you are right on both counts! Thanks I'll look into both of those!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.