Golang JSON编码,可用于JavaScript解析 [英] 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并将其发送的代码如下:
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)
}
}
当我使用内置的JSON编码器中的Golang对其进行编码时,字段名称显示时不带引号,这会阻止node.js中的JSON.parse函数读取内容. 有人知道解决方案吗?
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?
谢谢!
推荐答案
这是我的错误.问题出在Javascript代码中. 我正在使用node.js请求包,它似乎默认解析JSON响应.在以下代码中,response.body已经是一个包含JSON字符串的解析内容的映射:
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...
});
这篇关于Golang JSON编码,可用于JavaScript解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!