JSON.Stringify fails on Scripting.Dictionary objects

前端 未结 3 619
暗喜
暗喜 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 04:43

    Javascript’s for...in construct (which is used in the JSON serializer you refer to) only works on native JS objects. To enumerate a Scripting.Dictionary’s keys, you need to use an Enumerator object, which will enumerate the keys of the Dictionary.

    Now the JSON.stringify method has a nifty way of allowing custom serialization, by checking for the presence of a toJSON method on each property. Unfortunately, you can’t tack new methods on existing COM objects the way you can on native JS objects, so that’s a no-go.

    Then there’s the custom stringifier function that can be passed as second argument to the stringify method call. That function will be called for each object that needs to be stringified, even for each nested object. I think that could be used here.

    One problem is that (AFAIK) JScript is unable to differentiate VBScript types on its own. To JScript, any COM or VBScript object has typeof === 'object'. The only way I know of getting that information across, is defining a VBS function that will return the type name.

    Since the execution order for classic ASP files is as follows:

    • And here we have the full implementation of the vbsStringifier that is passed along as second parameter to JSON.stringify:

      
      

      Of course, switching back and forth between scripting engines isn’t very efficient (i.e. calling a VBS function from JS and vice versa), so you probably want to try to keep that to a minimum.


      Also note that I haven’t been able to test this, since I no longer have IIS on my machine. The basic principle should work, I’m not 100% certain of the possibility to pass a JScript function reference from VBScript. You might have to write a small custom wrapper function for the JSON.stringify call in JScript:

      
      

      after which you can simply adjust the VBScript call:

      <%
          Response.Write JSONStringify(oProd)
      %>
      

提交回复
热议问题