如何转换此
qqqq%2Fwwww%3Feeee%26rrrr%3Dtttt
到这个
qqqq/wwww?eeee&rrrr=tttt
有简单的解码方法吗?
我们有一个编码库函数Uri.EscapeDataString
的URI,但我们没有要解码的反向函数(这可能是疏忽)。请随时在上建议此功能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在1去:
// Uri.Decode()
// Ref: https://learn.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,