Unmarshalling JSON with Null Boolean Values in Go

Whilst working on Monitoring Agent 1 , which is written in Go , I added validation for the configuration file read by the Monitoring Agent process when it is started. The configuration file is formatted in JSON and unmarshalled to a struct type.

When a mandatory configuration item is added and an administrator upgrades Monitoring Agent , they should see a useful error message about the missing configuration item instead of having the process run with unpredictable or insecure results.

The program therefore needs to ensure certain values have been set. In Go , when storage is allocated for a variable without explicit initialization, the variable is given the zero value for it’s type. For a bool type, this is 0 which is also false .

That means when configuration data is read from a file and unmarshalled, the code needs to work out whether a bool value is either false or omitted.

Solution 1: Use Pointers

Instead of defining bool types for members of the struct that JSON is unmarshaled into, we could use pointers ( *bool ) instead.

When a value is not provided to json.Unmarshal() for a member of the struct , the pointer value will be nil. Thus mystruct.var == nil can be used to see the value was included in the JSON.

Go Playground example.

The downside of this solution is that interrogating or changing the value means dereferencing or indirecting the variable, for example *input.IsGoodCode = false , as opposed to input.IsGoodCode = false .

Solution 2: Use a Custom Struct Type

I don’t like smearing code with unnecessary punctuation. Fortunately, there is another way. Instead of relying on pointers, a struct type can be used:

This is a struct with two members. IsTrue is the actual value of the bool . HasValue indicates whether or not IsTrue has been explicitly set.

Instead of input.IsGoodCode != nil and *input.IsGoodCode = true we can write input.IsGoodCode.HasValue and input.IsGoodCode.IsTrue = yes .

Before the NullBool struct can be used, we have to create a struct to represent the JSON data:

The final step is changing the way that the code unmarhals JSON into the NullBool struct .

Taking advantage of Go’s UnmarshalJSON() interface , a method on NullBool is implemented with the signature UnmarshalJSON(b []byte) error :

This method is run by any call to json.Unmarshal() when populating any instance of the NullBool struct , for which data is provided .

If a key defined in the struct representing the JSON data is omitted from the JSON string which is unmarshalled into it, then NullBool ’s UnmarshalJSON() is not run.

With bool values initiatlised to 0 ( false ), both IsTrue and HasValue will be false for any instance of NullBool that has not been populated by the unmarshalling of JSON.

Conversely, we know that instances of NullBool with IsTrue:false and HasValue:true have a corresponding key in a JSON string with a value of false .

Click here for the full Go Playground example.

Go is well documented, widely supported and easy to learn. Like many languages that use zero type initialisation , extra care needs to be afforded in some situations, like unmarshalling JSON.

The UnmarshalJSON interface is very powerful because it gives developers control over how custom types are populated when unmarshalling JSON. Not only can it be used to change the way objects are hydrated, but it can be used to add additional validation.

  • Variables - golang.org
  • The Zero Value - golang.org
  • Interface Types - golang.org
  • Struct Types - golang.org

A collaborative open source effort with four other members of my team  ↩︎

programming

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How can I track down a function return mismatch in Go?

How can I track down a function return mismatch in Golang? In two different build environments I am seeing a difference. Both cases should be Visual Studio Code remote to a Linux box, using Go 1.12 in module mode. The broken case is where I am driving the build using the Golang:1.12 Docker image. Below is simplified from where I'm seeing the problem.

So for this sample, derived from https://github.com/satori/go.uuid :

The unexpected build error is:

In the environment where I encounter this problem, in Visual Studio Code when I hover with mouse over the call to uuid.NewV4() I see:

and hover over uuid shows:

I may switch to a different uuid package to work around this -- but I want to understand better how to figure this out.

learning2learn's user avatar

  • Use Go modules to pin the version of go.uuid. –  Volker Commented Apr 16, 2020 at 14:06
  • @Volker thanks -- I had it on 1.2.0 in go.mod, now forced to 1.2.1, seems to work as I had expected now. –  learning2learn Commented Apr 16, 2020 at 14:44

I guess problem is in different github.com/satori/go.uuid module versions. You can see, that NewV4 function signature was updated to NewV4() (uuid.UUID, error) in latest version v1.2.0 . Before that it was func NewV4() UUID

Then resolve to a specific version as in this question:

How to point Go module dependency in go.mod to a latest commit in a repo?

Grigoriy Mikhalkin's user avatar

  • Thanks, do you know how VSCode ( guess via gopls) picks the function help information it displays? –  learning2learn Commented Apr 16, 2020 at 14:51
  • @learning2learn My guess is gopls, yes. But really, i don't know about VSCode internals(and don't use it) ;) –  Grigoriy Mikhalkin Commented Apr 16, 2020 at 14:55

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged go or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • What came of the Trump campaign's complaint to the FEC that Harris 'stole' (or at least illegally received) Biden's funding?
  • If a friend hands me a marijuana edible then dies of a heart attack am I guilty of felony murder?
  • How will the Polaris Dawn cabin pressure and oxygen partial pressure dovetail with that of their EVA suits? (100% oxygen?)
  • Why are my empty files not being assigned the correct mimetype?
  • Working principle of the Zener diode acting as a voltage regulator in a circuit
  • What would the natural diet of Bigfoot be?
  • How do you ensure that calendar invites won't be moved out of your inbox when your rules are executed?
  • Remove spaces from the 3rd line onwards in a file on linux
  • How to make conditions work in Which?
  • What prevents indoor climbing gyms from making a v18 boulder even if one hasn't been found outside?
  • LaTeX labels propositions as Theorems in text instead of Propositions
  • Why does friendship seem transitive with befriended function templates?
  • Where did Gomez Addams get his last name?
  • Second cohomology of nonabelian finite simple group vanishes.
  • How did NASA know figure out when and where the Apollo capsule would touch down on the ocean?
  • Overstaying knowing I have a new Schengen visa
  • Why doesn't SiLU suffer from a worse version of a "dying ReLU" problem?
  • When deleting attribute from GDB file all the fields in the remaining attributes get deleted as well in QGIS
  • How can I analyze the anatomy of a humanoid species to create sounds for their language?
  • Exam package: \numpages wrong when enforcing an even number of pages
  • Can a V22 Osprey operate with only one propeller?
  • MSSQL - query runs for too long when filtering after a certain date
  • BASH - Find file with regex - Non-recursively delete number-only filenames in directory
  • Is Produce Flame a spell that the caster casts upon themself?

assignment mismatch 1 variable but json.marshal returns 2 values

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

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

assignment mismatch: 2 variables but uuid.NewV4 returns 1 values #100

@chingiz2387

chingiz2387 commented Sep 13, 2019

Hello everyone, I started experimenting with mod. When I initialize the modules in my project, all libraries are loaded and github.com/satori/go.uuid is loaded accordingly.. But when starting go run server.go, I get an error #0",
"severity": 8,
"message": "cannot initialize 2 variables with 1 values",
"source": "LSP",
"startLineNumber": 41,
"startColumn": 20,
"endLineNumber": 41,
"endColumn": 30
}

I am using vscode.

My project is outside gopath

@rajmaniar

rajmaniar commented Sep 18, 2019

I struggled with this today before I realized the api for NewV4 at the latest semver tag v1.2.0 has one return variable but the head of master branch on the repo has two.

vs

go modules will always try to collect the latest semver tag by default so you need to do something like:

  • 👍 15 reactions

Sorry, something went wrong.

@3013216027

3013216027 commented Sep 24, 2019

Same to me, the default behavior of go mod confuse with the old tag.
I wonder if it's possible to add a new version tag :)

  • 👍 3 reactions

@cameracker

cameracker commented Oct 16, 2019

this package is obsolete.

Recommend using

3013216027 commented Nov 5, 2019

@CameronAckermanSEL thks, I've moved to instead

  • 👍 2 reactions
  • 👎 1 reaction

No branches or pull requests

@rajmaniar

COMMENTS

  1. mongodb

    I've done almost everything but I have problem with json.marshal(). Can . Skip to main content. Stack Overflow. About; Products OverflowAI; ... It returns two values. The problem here is that you just give it one variable to get those two values: b := json.Marshal(result) So you just have to correct it this way: b, err := json.Marshal(result) ...

  2. go

    The string conversion you are trying to perform requires a single argument, but the json.Marshal function returns two ([]byte and error). You need to store the first return value and then do the conversion:

  3. go 我这里的代码一个不理解的报错,麻烦会的看下谢谢

    go 我这里的代码一个不理解的报错,麻烦会的看下谢谢. 凉瓜. 70 1 11 20. 发布于. 2019-04-09. 报错信息是:serviceservice.go:38:11: assignment mismatch: 2 variables but 1 values. 代码如下. package service. import (.

  4. Working with JSON Data in Go: A Guide to Marshalling and ...

    In this example, we define a Person struct with two fields, Name and Age. We create a Person object with some values, and then marshal it into a JSON string using the json.Marshal function. We ...

  5. Golang: Marshaling/Unmarshaling String Values and Arrays

    We can unmarshal the "value" from JSON into a variable of type "Value," as demonstrated in the snippet below: func (v ... if len (v) == 1 {return json. Marshal (v [0])} var vals [] string = [] string (v) return json. Marshal (vals)} In summary, this article provides a technique for custom marshaling and unmarshaling of a value that can either ...

  6. cmd/compile: incorrect typecheck error for multiple assignment

    % cat /tmp/x.go package p func f() string func _() { x := f(), 1, 2 } % go tool compile /tmp/x.go /tmp/x.go:6:4: assignment mismatch: 1 variables but f returns 3 values % Narrator: f does not return 3 values. Been this way back to Go 1.1...

  7. Assignment mismatch: 2 variable but returns three values?

    func2() returns three values, and you assign the returned values of func2 to two variables. func2 expects three variables. If you post the definition of func2 we can point out the specific location where this is happening, but it might be more useful for the long term to go through the Go tour as Jakob above suggests.

  8. Guide to Marshalling and Unmarshalling in Golang

    fmt.Println(unmarshalledP) We unmarshal the JSON back into a Person struct using json.Unmarshal. Go's nice type system handles matching the JSON properties back to the Person struct ...

  9. Custom Error Marshaling to JSON in Go

    In this post I want to go through an example of data marshaling in the Go language. The example starts with this snippet:package mainimport ( "encoding/json" "errors" "fmt")type AModel struct { Name string Errors []error}func main() { amodel := A

  10. Trying to understand json.unmarshal

    go:51: assignment count mismatch: 2 = 1. errors. I'm working my way through the book as well as the Udemy training. I think I get the general idea that for things like this one: Executes the GET request and is returned a byte array. Passes the byte array to ioutil and ReadAll to convert that to a slice of unsigned int8 values.

  11. Unmarshalling JSON with Null Boolean Values in Go

    Instead of defining bool types for members of the struct that JSON is unmarshaled into, we could use pointers (*bool) instead. When a value is not provided to json.Unmarshal() for a member of the struct, the pointer value will be nil. Thus mystruct.var == nil can be used to see the value was included in the JSON.

  12. Error: (random.go) assignment mismatch: 2 variables but 1 values

    Error: (random.go) assignment mismatch: 2 variables but 1 values #355. Closed gencer opened this issue Aug 1, 2018 · 3 comments Closed Error: (random.go) assignment mismatch: 2 variables but 1 values #355. gencer opened this issue Aug 1, 2018 · 3 comments Comments. Copy link Contributor.

  13. table/table.go:357:7: assignment mismatch: 1 variable but z

    Saved searches Use saved searches to filter your results more quickly

  14. assignment mismatch: 2 variables but uuid.NewV4 returns 1 values

    assignment mismatch: 2 variables but uuid.NewV4 returns 1 values #106. ... Open assignment mismatch: 2 variables but uuid.NewV4 returns 1 values #106. barry-en opened this issue Mar 5, 2020 · 6 comments Comments. Copy link barry-en commented Mar 5, 2020. I use go mod go mod init

  15. assignment mismatch: 2 variables but uuid.NewV4 returns 1 values

    assignment mismatch: 2 variables but uuid.NewV4 returns 1 values #34280. Closed chingiz2387 opened this issue Sep 13, 2019 · 3 comments Closed assignment mismatch: 2 variables but uuid.NewV4 returns 1 values #34280. chingiz2387 opened this issue Sep 13, 2019 · 3 ... "cannot initialize 2 variables with 1 values", "source": "LSP ...

  16. Golang Basics

    ./prog.go:8:7: assignment mismatch: 1 variable but fmt.Printf returns 2 values ./prog.go:9:2: cannot refer to unexported name fmt.println Explanation: The above program will generate a syntax error, because the function fmt.Printf() returns two values but we used only one value as an lvalue. Golang Find Output Programs »

  17. How can I track down a function return mismatch in Go?

    ./main.go:11:5 assignment mismatch: 2 variables but uuid.NewV4() returns 1 values In the environment where I encounter this problem, in Visual Studio Code when I hover with mouse over the call to uuid.NewV4() I see: func uuid.NewV4() (uuid.UUID, error) uuid.NewV4 on pkg.go.dev NewV4 returns random generated UUID. and hover over uuid shows:

  18. assignment mismatch: xlsx.GetRows · Issue #75 · shenwei356/csvtk

    Saved searches Use saved searches to filter your results more quickly

  19. assignment mismatch: 2 variables but uuid.NewV4 returns 1 values

    assignment mismatch: 2 variables but uuid.NewV4 returns 1 values #100. Open chingiz2387 opened this issue Sep 13, 2019 · 4 comments Open assignment mismatch: 2 variables but uuid.NewV4 returns 1 values #100. ... I struggled with this today before I realized the api for NewV4 at the latest semver tag v1.2.0 has one return variable but the head ...