Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to decode with Struct pointer #156

Closed
AlexandreRzc opened this issue Feb 28, 2019 · 1 comment · Fixed by #205
Closed

How to decode with Struct pointer #156

AlexandreRzc opened this issue Feb 28, 2019 · 1 comment · Fixed by #205

Comments

@AlexandreRzc
Copy link

AlexandreRzc commented Feb 28, 2019

Hi
I would like to decode this kind of structure with pointers and nested structure with pointers
and keeping the field in input as a flattened map and using squash
But got an error :

  • Family: unsupported type for squash: ptr

I would like to achieve this results

  • If LastName is filled with value "test" : Family is initialiazed and Lastname equals "test" and json ouput is
    {"family":{"lastname":"test"},"city":"San Francisco","firstname":"Mitchell"}

  • If LastName is nil : Family is nil and json output is
    {"city":"San Francisco","firstname":"Mitchell"}

Thanks

package main

import (
	"encoding/json"
	"fmt"
	"github.com/mitchellh/mapstructure"
)

func main() {
	type Family struct {
		LastName *string \`json:"lastname,omitempty"\`
	}
	type Location struct {
		City string \`json:"city,omitempty"\`
	}
	type Person struct {
		*Family \`json:"family,omitempty" mapstructure:",squash"\`
		Location  \`mapstructure:",squash"\`
		FirstName string \`json:"firstname,omitempty"\`
	}

	input := map[string]interface{}{
		"FirstName": "Mitchell",
		"City":      "San Francisco",
	}

	var result Person
	err := mapstructure.Decode(input, &result)
	if err != nil {
		panic(err)
	}
	res, err := json.Marshal(result)
	fmt.Println(string(res)) 

}
@mitchellh
Copy link
Owner

This isn't currently supported it appears but I'd be happy to add this if there is a PR!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants