0
type MiddleMan struct {
    User CompletedByUser `json:"user"`
}
type CompletedByUser struct {
    DisplayName string `json:"displayName"`
    Id          string `json:"id"`
}

Using the following types, I run the code

shorterJsonString := `{
    "user":{
        "displayName":null,
        "id":"a03dfee5-a754-4eb9"
    }
 }`

if !json.Valid([]byte(shorterJsonString)) {
    log.Println("Not valid")
}
var middleMan models.MiddleMan

newReader := strings.NewReader(shorterJsonString)
json.NewDecoder(newReader).Decode(&middleMan)

log.Println(middleMan)

Unfortunately, the decoder is seemingly broken for nested objects. Rather than spitting out actual objects, the print prints out

{{ a03dfee5-a754-4eb9 }}

It seems to flatten the whole thing into the id field. What is going on here?

1
  • 3
    middleMan, which you are printing, is of type models.MiddleMan. It has nothing to do with JSON, and thus will receive fmt-style formatting from log.Println, which likes to omit field names as well as null fields. You could get it to be slightly more verbose using log.Printf("%+v\n", middleMan). What are you trying to accomplish? Commented Dec 1, 2021 at 9:09

1 Answer 1

4

What did you expect to happen / get printed?

The log package (which uses the fmt package) prints structs enclosed in braces, listing field values separated by spaces.

Your MiddleMan has a single field, so it'll look like this:

{field}

Where field is another struct of type CompletedByUser, which has 2 fields, so it'll look like this:

{{field1 field2}}

Where field is of string type, being the empty string, so you'll see the value of field2 prefixed with a space:

{{ a03dfee5-a754-4eb9}}

If you print it adding field names:

log.Printf("%+v", middleMan)

You'll see an output like:

{User:{DisplayName: Id:a03dfee5-a754-4eb9}}

Using another (Go-syntax) format:

log.Printf("%#v", middleMan)

Output:

main.MiddleMan{User:main.CompletedByUser{DisplayName:"", Id:"a03dfee5-a754-4eb9"}}

Try this on the Go Playground.

Sign up to request clarification or add additional context in comments.

1 Comment

I expected it to print the whole thing, and not unexpectedly omit most of the object. This seems to me crazy behavior. I would expect a simple Println("smth") to simply print "smth", and not filter it according to its own bias, as it does in most languages.

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.