英文:
Why is the result of the gourl.ParseQuery method so unexpected?
问题
这个程序的结果是{"x":["1 1 3"], "y":["2", "3"]}
。但为什么不是{"x":["1+1+3"], "y":["2", "3"]}
呢?要得到期望的结果"1+1+3"
,你需要做什么?
import (
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
)
func main() {
m, err := url.ParseQuery(`x=1+1+3&y=2&y=3`)
if err != nil {
log.Fatal(err)
}
fmt.Println(toJSON(m))
}
func toJSON(m any) string {
js, err := json.Marshal(m)
if err != nil {
log.Fatal(err)
}
return strings.ReplaceAll(string(js), ",", ", ")
}
沙箱链接:https://go.dev/play/p/o0TiRTVpaQk
{"x":["1+1+3"], "y":["2", "3"]}
英文:
The result of this program is {"x":["1 1 3"], "y":["2", "3"]}
.
But why is not {"x":["1+1+3"], "y":["2", "3"]}
?
What do I need to do to get the expected result"1+1+3"
?
import (
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
)
func main() {
m, err := url.ParseQuery(`x=1+1+3&y=2&y=3`)
if err != nil {
log.Fatal(err)
}
fmt.Println(toJSON(m))
}
func toJSON(m any) string {
js, err := json.Marshal(m)
if err != nil {
log.Fatal(err)
}
return strings.ReplaceAll(string(js), ",", ", ")
}
Sandbox: https://go.dev/play/p/o0TiRTVpaQk
{"x":["1+1+3"], "y":["2", "3"]}
答案1
得分: 0
url.ParseQuery
将+
替换为
相关代码片段:
case '+':
if mode == encodeQueryComponent {
t.WriteByte(' ')
} else {
t.WriteByte('+')
}
解决方案是对+
进行编码(将它们替换为%2B
)
如下所示:
import (
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
)
func main() {
m, err := url.ParseQuery(`x=1%2B1%2B3&y=2&y=3`)
if err != nil {
log.Fatal(err)
}
fmt.Println(toJSON(m))
}
func toJSON(m any) string {
js, err := json.Marshal(m)
if err != nil {
log.Fatal(err)
}
return strings.ReplaceAll(string(js), ",", ", ")
}
英文:
url.ParseQuery
replaces +
with
relevant code fragment:
case '+':
if mode == encodeQueryComponent {
t.WriteByte(' ')
} else {
t.WriteByte('+')
}
the solution is to encode +
(replace them with %2B
)
like so:
import (
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
)
func main() {
m, err := url.ParseQuery(`x=1%2B1%2B3&y=2&y=3`)
if err != nil {
log.Fatal(err)
}
fmt.Println(toJSON(m))
}
func toJSON(m any) string {
js, err := json.Marshal(m)
if err != nil {
log.Fatal(err)
}
return strings.ReplaceAll(string(js), ",", ", ")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论