JSON.Stringify fails on Scripting.Dictionary objects

前端 未结 3 613
暗喜
暗喜 2021-01-07 03:58

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

3条回答
  •  长发绾君心
    2021-01-07 05:02

    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))
    

    Known issues:

    • The closing } 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.

提交回复
热议问题