Creating JSON array in Go

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

Creating JSON array in Go

问题

如何使用Go构建和发送JSON数组?

例如:

{ myArray: ["one", "two", "three"] }

目前,我能做到的最接近的是将JSON作为字符串发送到浏览器,像这样:

{ myArrayString: '[\"once\", \"two\", \"three\"]' }

这不是我想要实现的目标。

英文:

How do I construct and send a JSON array with Go?

For example:

{ myArray: ["one", "two", "three"] }

At the moment the closest I can get it sending JSON down to the browser as a string like this:

{ myArrayString: '["once", "two", "three"]' } 

Which is not what I'm trying to achieve.

答案1

得分: 8

以下是翻译好的内容:

非常“直接”,正如@swoogan所评论的:

package main

import (
	"encoding/json"
	"fmt"
)

type myJSON struct {
	Array []string
}

func main() {
	jsondat := &myJSON{Array: []string{"one", "two", "three"}}
	encjson, _ := json.Marshal(jsondat)
	fmt.Println(string(encjson))
}

演示可在此处查看。

英文:

Quite straightforward as @swoogan comments:

package main

import (
	"encoding/json"
	"fmt"
)

type myJSON struct {
	Array []string
}

func main() {
	jsondat := &myJSON{Array: []string{"one", "two", "three"}}
	encjson, _ := json.Marshal(jsondat)
	fmt.Println(string(encjson))
}

Demo avaliable here.

答案2

得分: 2

你需要导入"encoding/json",然后使用json.Marshal和你的结构体进行操作。

https://golang.org/pkg/encoding/json/#example_Marshal

英文:

You need to import "encoding/json" and then use json.Marshal with your structure.

https://golang.org/pkg/encoding/json/#example_Marshal

huangapple
  • 本文由 发表于 2015年10月26日 23:35:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/33349695.html
匿名

发表评论

匿名网友

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

确定