将表示JSON的字符串切片转换为JSON并响应请求。

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

Converting an slice of strings that represent JSON to JSON and responding to a request

问题

我有一个字符串切片([]string),想要将其转换为JSON格式。

这是当我使用fmt.Println()打印切片时的样子:

[
    {"field1": "data1",  "field2": "data2"},
    {"secondField1": "data1",  "secondfield2": "data2"}
]

编辑

我想将其作为HTTP请求的响应发送。

这是我的代码。

jsonString := `"{"field1": "data1",  "field2": "data2"}",
               "{"secondField1": "data1",  "secondfield2": "data2"}"`

json.NewEncoder(w).Encode(jsonString)

这里的w是http.ResponseWriter类型的变量。


回答

mkopriva在原问题中发表了评论,他提供的解决方案有效。

这是他提供的链接。

https://play.golang.org/p/n5b5ec4297K

这是对我有效的代码(你可以在playground链接中找到):

jsonArray := make([]json.RawMessage, len(stringSlice))

for i := range stringSlice {
    jsonArray[i] = json.RawMessage(stringSlice[i])
}

if err := json.NewEncoder(os.Stdout).Encode(jsonArray); err != nil {
    panic(err)
}
英文:

I have a slice of strings ([]string) and would like to convert it to JSON.

Here is what my slice looks like when I fmt.Println()

[
    {\"field1\": \"data1\",  \"field2\": \"data2\"},
    {\"secondField1\": \"data1\",  \"secondfield2\": \"data2\"}
]

EDIT

I want to send it as a response to a HTTP request.

Here is my code.

jsonString := `"{"field1": "data1",  "field2": "data2"}",
               "{"secondField1": "data1",  "secondfield2": "data2"}"`

json.NewEncoder(w).Encode(jsonString)

w is a http.ResponseWriter


ANSWER

mkopriva has commented on the original question and his solution worked.

Here is the link he provided.

https://play.golang.org/p/n5b5ec4297K

Here is the code that worked for me (you can find it in the playground link)

	jsonArray := make([]json.RawMessage, len(stringSlice))

	for i := range stringSlice {
		jsonArray[i] = json.RawMessage(stringSlice[i])
	}

	if err := json.NewEncoder(os.Stdout).Encode(jsonArray); err != nil {
		panic(err)
	}

答案1

得分: 0

根据你的问题,我理解你想要将 JSON 写入 http.ResponseWriter。在这种情况下,我建议采用以下方法:

func handle(w http.ResponseWriter, r *http.Request) {
   myslice := []string{"", "", ""}
   data, err := json.Marshal(myslice)
   if err != nil {
       log.Println("could not marshal", err)
       return
   }
   w.Write(data)
}

请注意,这里的错误处理不太好,并且也许你需要在头部添加一些关于内容类型的信息,但这超出了这个示例的范围。

英文:

From your question I understand that you want to write the json on a http.ResponseWriter. In that case I would suggest an approach like this:

func handle(w http.ResponseWriter, r *http.Request) {
   myslice := []string{"", "", ""}
   data, err := json.Marshal(myslice)
   if err != nil {
	   log.Println("could not marshal", err)
	   return
   }
   w.Write(data)
}

Please note that the error handling is not so nice here, and perhaps you would need to add something about content-type to the header, but that is beyond this example.

答案2

得分: 0

mkopriva对原始问题进行了评论,他的解决方案有效。

这是他提供的链接。

https://play.golang.org/p/n5b5ec4297K

以下是对我有效的代码(你可以在playground链接中找到):

    jsonArray := make([]json.RawMessage, len(stringSlice))

    for i := range stringSlice {
        jsonArray[i] = json.RawMessage(stringSlice[i])
    }

    if err := json.NewEncoder(os.Stdout).Encode(jsonArray); err != nil {
        panic(err)
    }
英文:

ANSWER

mkopriva has commented on the original question and his solution worked.

Here is the link he provided.

https://play.golang.org/p/n5b5ec4297K

Here is the code that worked for me (you can find it in the playground link)

    jsonArray := make([]json.RawMessage, len(stringSlice))

    for i := range stringSlice {
        jsonArray[i] = json.RawMessage(stringSlice[i])
    }

    if err := json.NewEncoder(os.Stdout).Encode(jsonArray); err != nil {
        panic(err)
    }

huangapple
  • 本文由 发表于 2021年10月6日 14:48:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/69461047.html
匿名

发表评论

匿名网友

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

确定