英文:
Sending JSON from server requires JSON.parse twice
问题
由于Go服务器生成的JSON字符串中包含转义字符,因此在JavaScript中解析时需要调用JSON.parse两次才能创建对象。你的服务器代码有一些问题,导致生成的JSON字符串不正确。
你可以尝试修改服务器代码如下:
import "encoding/json"
func generateJSON() string {
mydict := make(map[string]mystruct)
// 添加mydict的键值对
jsonData, err := json.Marshal(mydict)
if err != nil {
// 错误处理
}
return string(jsonData)
}
这样生成的JSON字符串将是有效的,你只需要在JavaScript中调用一次JSON.parse即可创建对象。
英文:
For some reason I have to call JSON.parse twice to create an object in JavaScript. I'm generating JSON from a Go (Golang) server.
This is the JavaScript code I'm using.
ws.onmessage = function(e) {
console.log(e.data);
console.log(JSON.parse(e.data));
console.log(JSON.parse(JSON.parse(e.data)));
};
And this is what I saw in Chrome's console.
"{\"hello\":\"world\"}"
{"hello":"world"}
Object {hello: "world"}
This is how I'm generating JSON on the server side. I suspect my server code is wrong.
var jsonBuffer bytes.Buffer
jsonBuffer.WriteString("{")
for key, value := range mydict {
jsonBuffer.WriteString(`"` + key `":"` + value + `"`)
}
jsonBuffer.WriteString("}")
return jsonBuffer.String()
This is a simplification of what I'm working on. In reality, mydict
is defined as map[string]mystruct
.
mystruct
is something like this:
type mystruct struct {
Foo int
Bar float64
}
答案1
得分: 0
你为什么要手动构建 JSON 响应?我建议使用 json 包。你的代码应该类似于这样:
package main
import (
"fmt"
"encoding/json"
)
type Mystruct struct {
Foo int
Bar float64
}
func main() {
m := Mystruct{1, 100}
j, _ := json.Marshal(m)
fmt.Print(string(j))
}
英文:
Why are you building the json response by hand? I would suggest to use the json package. Your code would look something like this
package main
import (
"fmt"
"encoding/json"
)
type Mystruct struct {
Foo int
Bar float64
}
func main() {
m := Mystruct{1,100}
j, _ := json.Marshal(m)
fmt.Print(string(j))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论