Golang JSON编码,用于parsingJavaScript

我有这样的结构:

type User struct { Login string `json:",string"` PasswordNonce Nonce `json:",string"` PasswordHash HashValue `json:",string"` CreatedOn time.Time `json:",string"` Email string `json:",string"` PhoneNumber string `json:",string"` UserId Id `json:",string"` } 

生成JSON并发送它的代码如下所示:

 func AddUserHandler(w http.ResponseWriter, r *http.Request) { var userRecord model.User encoder := json.NewEncoder(w) err = encoder.Encode(userRecord) if err != nil { panic(err) } } 

当我使用JSON编码器中构build的Golang对其进行编码时,字段名称不带引号,这会阻止node.js中的JSON.parse函数读取内容。 有谁知道这个解决scheme?

谢谢!

这是我的错误。 问题出在Javascript代码中。 我正在使用node.js请求包,它似乎默认parsingJSON响应。 在以下代码中,response.body已经是一个包含JSONstringparsing内容的映射:

 var request = require('request'); var options = { uri: 'http://localhost:3000/AddUser', method: 'POST', json: {} }; request(options, function(error, response, body) { console.log(error) console.log(response.body) console.log(response.body["UserId"]) data = response.body // data = JSON.parse(response.body) gives an error... }); 
 package main import ( "encoding/json" "math/rand" "net/http" "time" ) type Nonce [32]byte type HashValue [32]byte type Id [32]byte func MakeNonce() Nonce { return makeByte32() } func MakeHashValue() HashValue { return makeByte32() } func MakeId() Id { return makeByte32() } func makeByte32() [32]byte { bytes := [32]byte{} rand.Seed(time.Now().Unix()) for i, _ := range bytes { bytes[i] = byte(48 + (rand.Float64() * 10)) } return bytes } type User struct { Login string PasswordNonce Nonce PasswordHash HashValue CreatedOn time.Time Email string PhoneNumber string UserId Id } type myHandler struct { userRecord User } func (mh myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { encoder := json.NewEncoder(w) err := encoder.Encode(mh.userRecord) if err != nil { panic(err) } } func main() { user := User{ "test", MakeNonce(), MakeHashValue(), time.Now(), "test@test.com", "5195555555", MakeId(), } h := myHandler{user} http.ListenAndServe("localhost:4000", h) } 

你可以尝试使用json.Marshal

 jsonData, err := json.Marshal(data)