英文:
Transform a string thats contain a json to pure json format
问题
我有一个包含JSON的字符串。我需要将该字符串转换为JSON对象,以便在PUT请求中发送。这是我拥有的字符串:
{
"changed": "Jhon",
"created": "Marc",
"date_changed": "2020-10-06T12:51:36Z",
"date_created": "2020-10-06T12:51:36Z",
"title": "<h2></h2>"
}
编辑:
这段代码对我有用;用户在问题中提供了JSON字符串。
in := []byte(user)
var raw map[string]interface{}
if err := json.Unmarshal(in, &raw); err != nil {
panic(err)
}
fmt.Println(raw["changed"])
out, err := json.Marshal(raw)
if err != nil {
panic(err)
}
编辑2:这个也可以,并且更简单
strings.NewReader(user)
英文:
I have a string whats contains JSON. I need to transform that string to a JSON object in order to send it in a PUT request. Here is the string I have:
{
"changed": "Jhon",
"created": "Marc",
"date_changed": "2020-10-06T12:51:36Z",
"date_created": "2020-10-06T12:51:36Z",
"title": "\u003ch2\u003e\u003c/h2\u003e"
}
Edit:
This code works for me; the user represents the JSON string upper in the question.
in := []byte(user)
var raw map[string]interface{}
if err := json.Unmarshal(in, &raw); err != nil {
panic(err)
}
fmt.Println(raw["changed"])
out, err := json.Marshal(raw)
if err != nil {
panic(err)
}
Edit 2: this works, too, and is easier
strings.NewReader(user)
答案1
得分: 2
OP正在询问如何将包含JSON文档的字符串作为请求体使用。
http.NewRequest的body参数是一个io.Reader。可以使用strings.NewReader函数将字符串包装为io.Reader:
req, err := http.NewRequest("PUT", url, strings.NewReader(user))
英文:
OP is asking how to use a string
containing a JSON document as a request body.
The body argument to http.NewRequest is an io.Reader. Use the strings.NewReader function to wrap a string with an io.Reader:
req, err := http.NewRequet("PUT", url, strings.NewReader(user))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论