可以使用 Go 语言标准库中的 json 包来将 interface{} 类型的字符串数据转换成 JSON 字符串。

示例代码:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	str := 'hello world'
	data := interface{}(str)
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(string(jsonData))
}

输出结果:

'hello world'

在示例代码中,首先定义了一个字符串类型的变量 str,然后将其转换成 interface{} 类型的变量 data

接着,使用 json.Marshal() 函数将 data 变量转换成 JSON 格式的数据。如果转换过程中出现错误,就会返回一个非空的 err 对象。

最后,使用 fmt.Println() 函数输出 JSON 字符串。注意,由于 JSON 字符串是带有双引号的,因此需要使用 string() 函数将 []byte 类型的 jsonData 转换成字符串类型。

Golang interface{} 字符串转 JSON 字符串

原文地址: https://www.cveoy.top/t/topic/lNgg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录