英文:
Go Lang Return JSON
问题
我还是个新手,正在学习Go语言。我想让Go打印一个结构体,使得输出的键和值尽可能接近JSON格式。
目前我是将Go作为独立的服务器,在接收到GET请求时返回JSON。我希望将Go作为可执行文件放在我的主要Rails服务器上,并且只需使用类似Println的函数返回JSON(或者其他能够保持结构体形式的方法)。问题是,当我尝试这样做时,结构体的键并没有被打印出来,我基本上需要将键作为返回字符串的一部分。
有没有简单的方法可以保持正确的键和值(以及它们的类型,例如如果值是一个数组,保持数组的形式)?
英文:
Still pretty new with Go. I'm trying to get go to essentially print a struct with the keys and values as close to json as possible.
The way I'm currently doing this is having GO on it's own server and whenever a get request is made, it returns the JSON. I would like to have GO as an executable on my primary Rails server and just return the JSON with something like Println (or whatever would make it stay in struct form). The problem is when I try to go this route, the keys from the struct aren't printed with it and I would basically have to add the keys as part of the return string.
Is there a simple way to do this with keeping the correct keys and values (and their types, so if the value is an array, keep the array)
答案1
得分: 2
在Go语言中,将结构体打印为JSON格式并输出到标准输出是相当简单的:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
foo := struct {
Hello string
JSON string
}{
Hello: "world",
JSON: "stuff",
}
fmt.Printf("foo struct : %+v\n", foo)
if err := json.NewEncoder(os.Stdout).Encode(foo); err != nil {
log.Fatal(err)
}
}
这个程序将输出以下内容:
foo struct : {Hello:world JSON:stuff}
{"Hello":"world","JSON":"stuff"}
根据你的问题,我真的不明白你的意思。无论如何,如果你想将结构体打印为JSON格式,或者只是想尽可能接近JSON的格式打印结构体,你可以参考上述代码。
英文:
Printing a struct as JSON to STDOUT is fairly straight forward in Go:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
foo := struct {
Hello string
JSON string
}{
Hello: "world",
JSON: "stuff",
}
fmt.Printf("foo struct : %+v\n", foo)
if err := json.NewEncoder(os.Stdout).Encode(foo); err != nil {
log.Fatal(err)
}
}
http://play.golang.org/p/wqqGJ1V_Zg
That program will output the following:
foo struct : {Hello:world JSON:stuff}
{"Hello":"world","JSON":"stuff"}
From your question I really didn't understand what you meant. In any case, if you wanted to print the struct as JSON or if you just wanted to print the struct as close to JSON as possible your answer is there.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论