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

时间:2016-03-27 00:56:01

标签: powerbi powerquery m

如何转换

qqqq/wwww?eeee&rrrr=tttt

到这个

ssl.h

有简单的解码方法吗?

2 个答案:

答案 0 :(得分:3)

我们有一个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并利用Uri.Parts的URL解码功能,如:

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

答案 1 :(得分:0)

@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,