如何解码URIComponent? (例如:“%2F%3F%26%3D”->“/?&=”)

How to decodeURIComponent? (ex: "%2F%3F%26%3D" -> "/?&=")

如何转换这个

qqqq%2Fwwww%3Feeee%26rrrr%3Dtttt

至此

qqqq/wwww?eeee&rrrr=tttt

?

有没有简单的解码方法?

我们有一个 URI encoding 库函数,Uri.EscapeDataString 但我们没有逆向解码(这可能是一个疏忽)。欢迎在 https://ideas.powerbi.com

上建议此功能

如果有任何非 ASCII 字符,自己编写比文本替换“%”稍微复杂一些。

这是一个 M 实现,它构建字节然后将文本转换为 UTF-8 二进制文件:

let
    InputData = Csv.Document("a=b
=ab
ab=
abc☃def"),

    Uri.UnescapeDataString = (data as text) as text => let 
        ToList = Text.ToList(data),
        Accumulate = List.Accumulate(ToList, [ Bytes = {} ], (state, current) => 
            let
                HexString = state[HexString]?,
                NextHexString = HexString & current,
                NextState = if HexString <> null
                  then if Text.Length(NextHexString) = 2
                      then [ Bytes = state[Bytes] & Binary.ToList(Binary.FromText(NextHexString, BinaryEncoding.Hex)) ]
                      else [ HexString = NextHexString, Bytes = state[Bytes] ]
                  else if current = "%"
                      then [ HexString = "", Bytes = state[Bytes] ]
                  else [ Bytes = state[Bytes] & { Character.ToNumber(current) } ]
            in
                NextState),
        FromBinary = Text.FromBinary(Binary.FromList(Accumulate[Bytes]))
      in
        FromBinary,

    AddEscaped = Table.AddColumn(InputData, "Escaped", each Uri.EscapeDataString([Column1])),

    AddUnescaped = Table.AddColumn(AddEscaped, "Custom", each Uri.UnescapeDataString([Escaped]))
in
    AddUnescaped

(我为以上内容感到自豪,但我想到了一种更简单的方法,如果您知道所有数据都已正确编码。)

您可以将字符串连接成 URL 并利用 Uri.Parts 的 URL 解码功能,例如:

Uri.UnescapeDataString = (data as text) as text => 
    Uri.Parts("http://whatever?a=" & data)[Query][a],

@MikeHoney 代码的小扩展。 我想一次性解码完整的 URI:

// Uri.Decode()
// Ref: https://docs.microsoft.com/en-us/powerquery-m/uri-parts
// Encoded+Decoded "?" & "&" to non-URI chars so Uri.Parts() could convert entire URI in 1 go.
    Uri.Decode = (url as text) as text => 
        let t1 = Text.Replace (url, "?", Character.FromNumber (29) ), // ? -> <group separator> 
            t2 = Text.Replace (t1, "&", Character.FromNumber (30) ), // & -> <record separator>
            t3 = Uri.Parts("http://foo?a=" & t2)[Query][a],
            t4 = Text.Replace(t3, Character.FromNumber (29), "?" ),
            decoded = Text.Replace(t4, Character.FromNumber (30), "&" )
        in decoded,