Go: 将字符串数组转换为 JSON 数组字符串

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

Go: Convert Strings Array to Json Array String

问题

尝试将字符串数组转换为Go中的JSON字符串。但是我得到的只是一个数字数组。

我错过了什么吗?

package main

import (
	"fmt"
	"encoding/json"
)

func main() {
	var urls = []string{
		"http://google.com",
		"http://facebook.com",
		"http://youtube.com",
		"http://yahoo.com",
		"http://twitter.com",
		"http://live.com",
	}

	urlsJson, _ := json.Marshal(urls)
	fmt.Println(urlsJson)
}

在Go Playground上的代码:http://play.golang.org/p/z-OUhvK7Kk

英文:

Trying to convert a strings array to a json string in Go. But all I get is an array of numbers.

What am I missing?

package main

import (
	"fmt"
	"encoding/json"
)

func main() {
	var urls = []string{
		"http://google.com",
		"http://facebook.com",
		"http://youtube.com",
		"http://yahoo.com",
		"http://twitter.com",
		"http://live.com",
	}
	
	urlsJson, _ := json.Marshal(urls)
	fmt.Println(urlsJson)
}

Code on Go Playground: http://play.golang.org/p/z-OUhvK7Kk

答案1

得分: 14

通过调用marshal函数,你可以得到表示JSON字符串的编码(字节)。如果你想要得到字符串形式的JSON,你需要将这些字节转换为字符串。

fmt.Println(string(urlsJson))
英文:

By marshaling the object, you are getting the encoding (bytes) that represents the JSON string. If you want the string, you have to convert those bytes to a string.

fmt.Println(string(urlsJson))

答案2

得分: 1

另一种方法是直接使用os.Stdout.Write(urlsJson)

英文:

Another way is to use directly os.Stdout.Write(urlsJson)

答案3

得分: 0

你可以使用标准输出输出编码器:

package main

import (
   "encoding/json"
   "os"
)

func main() {
   json.NewEncoder(os.Stdout).Encode(urls)
}

或者使用字符串构建器:

package main

import (
   "encoding/json"
   "strings"
)

func main() {
   b := new(strings.Builder)
   json.NewEncoder(b).Encode(urls)
   print(b.String())
}

更多信息请参考:https://golang.org/pkg/encoding/json#NewEncoder

英文:

You could use stdout output encoder:

package main

import (
   "encoding/json"
   "os"
)

func main() {
   json.NewEncoder(os.Stdout).Encode(urls)
}

or a string builder:

package main

import (
   "encoding/json"
   "strings"
)

func main() {
   b := new(strings.Builder)
   json.NewEncoder(b).Encode(urls)
   print(b.String())
}

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

huangapple
  • 本文由 发表于 2014年7月11日 11:18:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/24689546.html
匿名

发表评论

匿名网友

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

确定