ChatGPT解决这个技术问题 Extra ChatGPT

Converting Go struct to JSON

I am trying to convert a Go struct to JSON using the json package but all I get is {}. I am certain it is something totally obvious but I don't see it.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func main() {
    user := &User{name:"Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Printf("Error: %s", err)
        return;
    }
    fmt.Println(string(b))
}

Then when I try to run it I get this:

$ 6g test.go && 6l -o test test.6 && ./test 
{}

v
vimdude

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

Note that you can add `json:"name"` to the end of the struct field definition to preserve the output name.
I see. I kinda like the language but I think some syntactical elements go to far. If the name of a struct member determines the behavior then this is just wrong.
Well, having the name determine the behavior can be debated if it is good or bad :) but it sure make it easy to know if a field is exported or not without having to check somewhere else.
@magiconair: The capitalization of the first rune determines visibility, is a much more reasonable idea than, "the name of a struct member determines the behavior". The visibility metadata needs to be stored somewhere and needs syntax to express it. Eventually it was determined that co opting the capitalization of the first char works best with fewest trade-offs. Before the Go1 release other schemes were tried and rejected.
I've come a long way since and like the language including the exporting by capitalization very much now.
p
pixel

Related issue:

I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.

Wasted a lot of time, so posting solution here.

In Go:

// web server

type Foo struct {
    Number int    `json:"number"`
    Title  string `json:"title"`
}

foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)

In JavaScript:

// web call & receive in "data", thru Ajax/ other

var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);

This writes the json with the initial letter capitalized. How can I write the json string in lower case? EDIT: Make sure to include the quotation marks lol. sigh.
A
Andrew

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:

the field's tag is "-", or

the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.


H
Hieu Vo

You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name     string `json:"name"`
    }{
        Name:     "customized" + u.name,
    })
}

func main() {
    user := &User{name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}


d
demented hedgehog

This is an interesting question, it is very easy using the new go versions. You should do this:

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string `json:"name"`
}

func main() {
    user := &User{name:"Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Printf("Error: %s", err)
        return;
    }
    fmt.Println(string(b))
}

Change this name to Name.