可以使用标准库中的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/zha 著作权归作者所有。请勿转载和采集!

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