Golang JSON编码,用于使用JavaScript进行解析

Golang JSON encoding for parsing with JavaScript

本文关键字:JavaScript JSON 编码 用于 Golang      更新时间:2023-09-26

我有一个这样的结构:

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)
    }
}

当我使用Golang内置的JSON编码器对其进行编码时,字段名称显示时不带引号,这会阻止node.js中的JSON.parse函数读取内容。有人知道解决这个问题的办法吗?

谢谢!

这是我的错误。问题出在Javascript代码中。我使用的是node.js请求包,它似乎默认解析JSON响应。在下面的代码中,response.body已经是一个包含JSON字符串解析内容的映射:
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)