将包含 JSON 的字符串转换为纯 JSON 格式。

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

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:

{
  &quot;changed&quot;: &quot;Jhon&quot;,
  &quot;created&quot;: &quot;Marc&quot;,
  &quot;date_changed&quot;: &quot;2020-10-06T12:51:36Z&quot;,
  &quot;date_created&quot;: &quot;2020-10-06T12:51:36Z&quot;,
  &quot;title&quot;: &quot;\u003ch2\u003e\u003c/h2\u003e&quot;
}

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, &amp;raw); err != nil {
		panic(err)
	}
	fmt.Println(raw[&quot;changed&quot;])
	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(&quot;PUT&quot;, url, strings.NewReader(user)) 

huangapple
  • 本文由 发表于 2022年3月4日 10:58:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/71346139.html
匿名

发表评论

匿名网友

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

确定