Home  >  Article  >  Backend Development  >  Why are the results of the gourl.ParseQuery method so unexpected?

Why are the results of the gourl.ParseQuery method so unexpected?

PHPz
PHPzforward
2024-02-10 16:50:071131browse

为什么 gourl.ParseQuery 方法的结果如此意外?

In PHP development, the gourl.ParseQuery method is widely used to parse URL query strings. However, sometimes we find that the results of this method are unexpected and confusing. Why does this accident happen? PHP editor Baicao will explore this problem in this article and provide some solutions. Let’s take a look!

Question content

The result of this program is{"x":["1 1 3"], "y":["2", "3"]}. But why 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"]}

Solution

url.parsequery Replace with

Related code snippets:

case '+':
            if mode == encodequerycomponent {
                t.writebyte(' ')
            } else {
                t.writebyte('+')
            }

The solution is to encode (replace with +)

like this:

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), ",", ", ")
}

The above is the detailed content of Why are the results of the gourl.ParseQuery method so unexpected?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete