Sample Code:
Dim myObject
Set myObject = JSON.parse(someJsonResponseFromTheServer)
myFunction(myObject.someProperty)
The Problem:
When code similiar to this is ran in my application, it throws a 500
error from the server with a message similar to "Object Does not support property or method 'someProperty'. What I would like to do to solve this problem is something like this:
Dim myObject
Set myObject = JSON.parse(someJsonResponseFromTheServer)
If myObject.someProperty Then
myFunction(myObject.someProperty)
End If
However, if I add the conditional, it throws the same error on the line with the conditional instead of the line with the method call.
My Question:
In ASP Classic, how do you detect if a property exists within an object without throwing an error?
On the assumption that you are including some runat="server" js file that provides you with the JSON parser then JSON.parse
is going to return a Javascript object.
If the above assumption is correct then the following ought to work:
If myObject.hasOwnProperty("someProperty") Then
myFunction(myObject.someProperty)
End If
One of the benefits of classic ASP is that it allows you to run both VBScript and JScript in the same page - thus you can use the power of both.
First, add this block of JScript code to your existing .asp
file:
<script language="JScript" runat="server">
function CheckProperty(obj, propName) {
return (typeof obj[propName] != "undefined");
}
</script>
And assuming VBScript is the default language in the page, you can call it from within your VBScript code like this:
Dim myObject
Set myObject = JSON.parse(someJsonResponseFromTheServer)
If CheckProperty(myObject, "someProperty") Then
myFunction(myObject.someProperty)
End If
Tested it with generic class object and it works fine - the JScript is compiled before the VBScript thus accessible to it.
Sadly, this usually means an 'on error' statement.
Private Function TestProperty()
Dim Success
Success = False
On Error Resume Next
' set for property here
Success = (Err.Number = 0)
On Error Goto 0
TestProperty = Success
Exit Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With