I am working on an ASP classic project where I have implemented the JScript JSON class found here. It is able to interop with both VBScript and JScript and is almost exactly
I ended up writing a function to serialize the Dictionary type myself. Unfortunately, you'll have to go in and do a find & replace on any failed dictionary serializations. ({}
) I haven't the time to figure out an automated way to do this. You're welcome to fork it on BitBucket.
Function stringifyDictionary( key, value, sp )
dim str, val
Select Case TypeName( sp )
Case "String"
sp = vbCrLf & sp
Case "Integer"
sp = vbCrLf & Space(sp)
Case Else
sp = ""
End Select
If TypeName( value ) = "Dictionary" Then
str = """" & key & """:{" & sp
For Each k in value
val = value.Item(k)
If Not Right(str, 1+len(sp)) = "{" & sp And Not Right(str, 1+len(sp)) = "," & sp Then
str = str & "," & sp
End If
str = str & """" & k & """: "
If TypeName( val ) = "String" Then
If val = "" Then
str = str & "null"
Else
str = str & """" & escapeJSONString( val ) & """"
End If
Else
str = str & CStr( val )
End If
Next
str = str & sp & "}"
stringifyDictionary = str
Else
stringifyDictionary = value
End If
End Function
Function escapeJSONString( str )
escapeJSONString = replace(replace(str, "\", "\\"), """", "\""")
End Function
This was written as a function to use with JSON.stringify's replace
argument (2nd arg). However you cannot pass a VBScript function as an argument. (From my experience) If you were to rewrite this function in JScript you could use it when you're calling JSON.stringify to ensure that Dictionaries do get rendered properly. See the readme on BitBucket for more on that. Here's how I implemented it:
dim spaces: spaces = 2
dim prodJSON: prodJSON = JSON.stringify( oProduct, Nothing, spaces)
prodJSON = replace(prodJSON, """Specs"": {}", stringifyDictionary("Specs", oProduct.Specs, spaces * 2))
}
for the Dictionary
serialization will be the same number of indentations as the properties it contains. I didn't have time to figure out how to deal with that without adding another argument which I don't want to do.