我正在使用一个带有json类的旧经典asp / vbscript应用程序。
我有一个字符串文字:asdf\\nsedfgs
例如多数民众赞成没有逃脱json或任何东西。字面意思是那些人物。
所以,要在JSON字符串中使用该值,它应该是这样的,对吗?
{"somedesc":"asdf\\\\nsedfgs"}
...转义了两个反斜杠字符。
然而,在离开JSON并回到字符串文字的路上,我们会做这样的事情(按此顺序)
val = Replace(val, "\""", """")
val = Replace(val, "\\", "\")
val = Replace(val, "\/", "/")
val = Replace(val, "\b", Chr(8))
val = Replace(val, "\f", Chr(12))
val = Replace(val, "\n", Chr(10))
val = Replace(val, "\r", Chr(13))
val = Replace(val, "\t", Chr(9))
...但是对于上面的字符串,这个replace()序列给出了不正确的解码值:
结果(注意换行符,因为4 \
被替换为2,然后\n
被替换为换行符
asdf\
sedfgs
所以问题:
asdf\\nsedfgs
?\n
与转义的chr(13)
?答案 0 :(得分:1)
重要的部分是将逃逸的反斜杠与字符串的其余部分隔离,以免它们干扰转义序列 - 您可以拆分字符串,稍后重新附加缺失的部分:
Const ENCODE = FALSE
Const DECODE = TRUE
val = "asdf\\\\nsedfgs"
val = JSON(val, DECODE)
MsgBox val
'Swap replacement values & dividers + concatenation characters
val = JSON(val, ENCODE)
MsgBox val
Function JSON(ByVal str, ByVal mode)
Dim key, val
Set d = CreateObject("Scripting.Dictionary")
d.Add "\/", "/"
d.Add "\b", Chr(8)
d.Add "\f", Chr(12)
d.Add "\n", Chr(10)
d.Add "\r", Chr(13)
d.Add "\t", Chr(9)
If mode Then
d.Add "\""", """"
d.Add "\\", "\"
div = "\\"
cat = "\"
key = d.Keys
val = d.Items
Else
d.Add "\\", "\"
d.Add "\""", """"
div = "\"
cat = "\\"
key = d.Items
val = d.Keys
End If
arr = Split(str, div)
For i = 0 To UBound(arr)
For j = 0 To UBound(key)
arr(i) = Replace(arr(i), key(j), val(j))
Next
output = output & arr(i)
If i <> UBound(arr) Then output = output & cat
Next
d.RemoveAll
JSON = output
End Function