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 the code provided at json.org. I am required to use VBScript for this project by the manager of my team.
It works very well on primitives and classes defined within ASP. But I have need for Dictionary objects which from my knowledge are only available through COM interop. (via Server.CreateObject("Scripting.Dictionary")
) I have the following class which represents a product: (ProductInfo.class.asp)
<%
Class ProductInfo
Public ID
Public Category
Public PriceUS
Public PriceCA
Public Name
Public SKU
Public Overview
Public Features
Public Specs
End Class
%>
The Specs
property is a Dictionary of key:value pairs. Here's how I'm serializing it: (product.asp)
<%
dim oProd
set oProd = new ProductInfo
' ... fill in properties
' ... output appropriate headers and stuff
Response.write( JSON.stringify( oProd ) )
%>
When I pass an instance of ProductInfo
to JSON.Stringify
(as seen above) I get something like the following:
{
"id": "1547",
"Category": {
"id": 101,
"Name": "Category Name",
"AlternateName": "",
"URL": "/category_name/",
"ParentCategoryID": 21
},
"PriceUS": 9.99,
"PriceCA": 11.99,
"Name": "Product Name",
"SKU": 3454536,
"Overview": "Lorem Ipsum dolor sit amet..",
"Features": "Lorem Ipsum dolor sit amet..",
"Specs": {}
}
As you can see, the Specs
property is an empty object. I believe that the JSON stringify method knows that the Specs
property is an object, so it appends the {}
to the JSON string around the stringified output. Which in this case is an empty string. What I expect it to show, however is not an empty object. See below:
"Specs": {
"foo":"bar",
"baz":1,
"etc":"..."
}
I believe the problem area of the JSON library is here: (json2.asp)
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
I postulate that the problem with the above code is that it assumes that all objects inherit from the Object
class. (The one that provides hasOwnProperty
) However I think that it's likely that COM objects don't inherit from the Object
class — or at least the same Object
class. Or at least don't implement whatever interface is required to do for ... in
on them.
Update: While I feel it is irrelevant for the question to be answered — I expect some sort of web client to request (via http) the JSON representation of this object or a collection of this object.
tl;dr The question: What should I do to make it so that the Scripting.Dictionary
can be output properly as JSON instead of failing and returning just an empty string? Do I need to 'reinvent the wheel' and write my own Dictionary
class in VBScript that does act as a normal object in ASP?