0

如何转换这个

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

对此

qqqq/wwww?eeee&rrrr=tttt

?

有没有简单的解码方法?

4

2 回答 2

5

我们有一个 URI编码库函数,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 并利用 URL 解码功能,Uri.Parts例如:

Uri.UnescapeDataString = (data as text) as text => 
    Uri.Parts("http://whatever?a=" & data)[Query][a],
于 2016-03-28T07:06:09.427 回答
0

@MikeHoney 代码的小扩展。我想在 1 中解码完整的 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,
于 2021-02-26T23:45:34.357 回答