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: json.Marshal() doesn't produce right result #61062

Closed
DiJester opened this issue Jun 29, 2023 · 3 comments
Closed

encoding/json: json.Marshal() doesn't produce right result #61062

DiJester opened this issue Jun 29, 2023 · 3 comments

Comments

@DiJester
Copy link

DiJester commented Jun 29, 2023

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

$ go version
go version go1.19.3 darwin/amd64

Does this issue reproduce with the latest release?

Not test yet

What operating system and processor architecture are you using (go env)?

MacOS

go env Output
$ go env

What did you do?

I run the code below

func main() {
	data := []byte{110, 117, 108, 108}

	list := []string{}

	err := json.Unmarshal(data, &list)
	if err != nil {
		fmt.Println(err)
	}

	if len(list) == 0 {

		fmt.Printf("list is: %+v \n\r", list)
		listData, err := json.Marshal(list)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Printf("list marshalled bytes are: %+v \n\r", listData)

	}

}

Why the unmarshalled listData is 
[110 117 108 108] , but not [91, 93]

What did you expect to see?

The marshlled bytes for list should be [91, 93]

What did you see instead?

The marshlled bytes for list is [110 117 108 108]

@Jorropo
Copy link
Member

Jorropo commented Jun 29, 2023

110 117 108 108 is literally the string null.
You are parsing null into a []string which gives you []string(nil), you are then serializing the []string(nil) you just got to the json object: null.

Everything in your example works like expected.

@bcmills
Copy link
Contributor

bcmills commented Jun 29, 2023

This seems to be working as documented (https://pkg.go.dev/encoding/json#Marshal):

Array and slice values encode as JSON arrays, except that … a nil slice encodes as the null JSON value.

@bcmills bcmills closed this as not planned Won't fix, can't repro, duplicate, stale Jun 29, 2023
@DiJester
Copy link
Author

This seems to be working as documented (https://pkg.go.dev/encoding/json#Marshal):

Array and slice values encode as JSON arrays, except that … a nil slice encodes as the null JSON value.

Thank you for your answers.

@golang golang locked and limited conversation to collaborators Jun 29, 2024
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

4 participants