Golang的JSON编码以便在JavaScript中解析

huangapple go评论104阅读模式
英文:

Golang JSON encoding for parsing with JavaScript

问题

我有一个类似这样的结构体:

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函数无法读取内容。
有人知道解决方法吗?

谢谢!

英文:

I have a struct like this:

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"`
}

The code that generates the JSON and sends it is the following:

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

When I encode it with the Golang built in JSON encoder, the field names appear without quotes, which prevents the JSON.parse function in node.js from reading the content.
Does anyone know a solution to that?

Thanks!

答案1

得分: 2

这是要翻译的内容:

这是我的错误。问题出在Javascript代码中。
我正在使用node.js的request包,它似乎默认解析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...
});
英文:

It was my mistake. The problem was in the Javascript code.
I am using the node.js request package, and it seems to parse JSON responses by default. In the following code, response.body is already a map containing the parsed contents of the JSON string:

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

答案2

得分: 1

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)
}
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)
}
英文:
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)
}

答案3

得分: 0

你可以尝试使用json.Marshal函数:

jsonData, err := json.Marshal(data)
英文:

Can you try using json.Marshal

jsonData, err := json.Marshal(data)

huangapple
  • 本文由 发表于 2013年12月16日 01:10:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/20597316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定