Golang 切片转 JSON 格式 - 示例代码
以下是用 Golang 将切片 all_url []string 转换为 JSON 格式并赋值给 json_res 的示例代码:
package main
import (
"encoding/json"
"fmt"
)
func main() {
all_url := []string{'http://example.com', 'https://google.com', 'https://facebook.com'}
json_res, err := json.Marshal(all_url)
if err != nil {
fmt.Println("Error while marshaling to JSON:", err)
return
}
fmt.Println(string(json_res))
}
在上面的代码中,我们首先定义了一个字符串类型的切片 all_url,其中包含三个 URL。然后,我们使用 json.Marshal 函数将 all_url 转换为 JSON 字符串,并将结果赋值给变量 json_res。如果在转换过程中出现了错误,我们将打印错误消息并退出程序。最后,我们将 json_res 转换为字符串并打印出来。
输出结果如下:
['http://example.com','https://google.com','https://facebook.com']
可以看到,输出结果是一个包含了所有 URL 的 JSON 数组。
原文地址: https://www.cveoy.top/t/topic/oNs0 著作权归作者所有。请勿转载和采集!