从服务器发送JSON需要进行两次JSON.parse解析。

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

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

huangapple
  • 本文由 发表于 2014年7月9日 04:20:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/24641039.html
匿名

发表评论

匿名网友

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

确定