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

encoding/json: How can I figure out default value from json decoder #38208

Closed
guiferpa opened this issue Apr 1, 2020 · 3 comments
Closed

encoding/json: How can I figure out default value from json decoder #38208

guiferpa opened this issue Apr 1, 2020 · 3 comments

Comments

@guiferpa
Copy link

guiferpa commented Apr 1, 2020

I am looking for some approach to work with default values from a json decoder.

What version of Go are you using (go version)?

go version go1.13 darwin/amd64

Example

type User struct {
    FirstName  string `json:"fname"`
    LastName   string `json:"lname"`
}
var user User
body := bytes.NewBufferString(`{ "fname": "test-fname", "lname": "" }`)
if err := json.NewDecoder(body).Decode(&user); err != nil {
    ...
}
var user User
body := bytes.NewBufferString(`{ "fname": "test-fname" }`)
if err := json.NewDecoder(body).Decode(&user); err != nil {
    ...
}

Both examples above will have the same output (user.LastName == "") but how can I figure out if one is default value from Go struct and the other it's a input from user?

I need this because of some validations in business rule inside of my app. If user put the field, for example lname I make one thing but if not I make another thing.

I just write this question in gopher#api Slack channel and the workaround was to use pointer, but for me it isn't elegant. Is there some other approach for this problem?

Many tks

@networkimprov
Copy link

networkimprov commented Apr 2, 2020

You could initialize var user with values that cannot appear in the input.

You'll prob get more help via golang-nuts for Q's like this. This issue tracker isn't used that way.

EDIT: possible string values: "\x00" or an invalid UTF-8 sequence.

@OneOfOne
Copy link
Contributor

OneOfOne commented Apr 2, 2020

This belongs on stackoverflow but no, pointer is the only way pretty much.

https://play.golang.org/p/L_WNxsPKPzH

@andybons
Copy link
Member

andybons commented Apr 3, 2020

Hi there,

Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.

For asking questions, see:

Please ask the question on one of the above forums.

(Quoted from https://golang.org/wiki/Questions)

@andybons andybons closed this as completed Apr 3, 2020
@golang golang locked and limited conversation to collaborators Apr 3, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants