-1

I have a web service which returns a json response as follows:

"database" ; True
"cpu usage" ; 30%
"connection response" ; 1
"memory" ; 48%

The requirement is to create a vb script which would read through the results, compare it against a set threshold and set a flag accordingly. That is, I need the result to say "green" if the value against "database" is "true", cpu usage is less than 80%, connection response is more than 0 and memory usage is less than 80%.

Could someone please help me with the above request. This is actually to be used with SCOM monitoring.

user692942
  • 16,398
  • 7
  • 76
  • 175
  • That JSON is malformed, it should be `"property name" : "property value"`. The semicolon *(`;`)* is a command termination character in JavaScript you should be using a colon *(`:`)* instead. – user692942 Dec 14 '16 at 10:55
  • Thanks Lankymart - this was a proposed response that I will be receiving from the webservice and hence I scribbled out something which I thought would be coming out from the webservice. The webservice itself has not been built yet. But i was trying to find out a way to monitor it. – mitheun sunny Dec 14 '16 at 11:42
  • Sorry I didn't get that from - *"I have a web service which returns a json response"*. If this is purely conceptional at the moment then this isn't the right place to ask as questions should have a clear problem and be easily re-creatable through a [mcve] for anyone trying to help. Please review [ask] before posting. – user692942 Dec 14 '16 at 11:53

1 Answers1

-1

Your JSON will be more like this. Note that I have changed the variable names to remove spaces - you will need to modify the code accordingly if these guesses were wrong. In JSON variable names and any non-numeric values are in quotes. Typically you would use a JSON parser to handle this but if it really is this simple you can use some simple string handling code to proceed.

{
"database": "true",
"cpu_usage": 30,
"connection_response": 1,
"memory": 48
}

Call this function passing it the JSON string that you get from the service. It works on the basis that a JSON string is a string and we can chop it about to get usable values IF it is of simple format. If it becomes a more complex message then you will need to search for a JSON parser for VB, or if the interface can respond in XML you will find it much easier to handle in VB.

This is VB6 code (easier for me to test with) - you will need to remove all of the 'as string', 'as integer' etc from the variable declares for VB Script. I have included a val() function for VBScript sourced from here though not tested with my function. You need val() as the JSON is string formatted and if you try to compare numeric values to strings you will get unexpected results.

'
' Function to return RED or GREEN depending on values in simple JSON
'
Function checkStatus(sJSON As String) As String

Dim aVals() As String, aParams() As String, i As Integer, sName As String, sVal As String
Dim bDatabase As Boolean, bCPU As Boolean, bConnection As Boolean, bMemory As Boolean

aVals = Split(sJSON, ",")
For i = 0 To UBound(aVals)

    aVals(i) = Trim(aVals(i)) ' remove any leading & trailing spaces
    aVals(i) = Replace(aVals(i), "{", "") ' remove braces open
    aVals(i) = Replace(aVals(i), "}", "") ' remove braces close
    aVals(i) = Replace(aVals(i), """", "") ' remove quotes > "database: true"
    Debug.Print "vals[" & i & "]=" & aVals(i)

    If Len(aVals(i)) > 0 Then ' should catch any dodgy JSON formatting but may need refinement

        aParams = Split(aVals(i), ":") ' split the line e.g. "database: true" > "database" and " true"
        If UBound(aParams) > 0 Then

            sName = LCase(Trim(aParams(0)))  ' now we have sName = "database"
            sVal = LCase(Trim(aParams(1)))   ' and sVal = "true"

            Select Case sName
                Case "database"

                    bDatabase = False
                    If sVal = "true" Then
                        bDatabase = True
                    End If

                Case "cpu_usage"
                    bCPU = False
                    If Val(sVal) > 80 Then
                        bCPU = True
                    End If

                Case "connection_response"
                    bConnection = False
                    If Val(sVal) > 0 Then
                        bConnection = True
                    End If


                Case "memory"
                    bMemory = False
                    If Val(sVal) < 80 Then
                        bMemory = True
                    End If


            End Select
        End If
    End If
Next i

checkStatus = "RED" ' default return value to indicate an issue

' compare the flags to decide if all is well.
If bDatabase And bCPU Then  'And bConnection And bMemory Then
    checkStatus = "GREEN"
End If


End Function

Function Val( myString )
' Val Function for VBScript (aka ParseInt Function in VBScript).
' By Denis St-Pierre.
' Natively VBScript has no function to extract numbers from a string.
' Based shamelessly on MS' Helpfile example on RegExp object.
' CAVEAT: Returns only the *last* match found
'         (or, with objRE.Global = False, only the *first* match)

    Dim colMatches, objMatch, objRE, strPattern

    ' Default if no numbers are found
    Val = 0

    strPattern = "[-+0-9]+"       ' Numbers positive and negative; use
                                  ' "ˆ[-+0-9]+" to emulate Rexx' Value()
                                  ' function, which returns 0 unless the
                                  ' string starts with a number or sign.
    Set objRE = New RegExp        ' Create regular expression object.
    objRE.Pattern    = strPattern ' Set pattern.
    objRE.IgnoreCase = True       ' Set case insensitivity.
    objRE.Global     = True       ' Set global applicability:
                                  '   True  => return last match only,
                                  '   False => return first match only.
    Set colMatches = objRE.Execute( myString )  ' Execute search.
    For Each objMatch In colMatches             ' Iterate Matches collection.
        Val = objMatch.Value
    Next
    Set objRE= Nothing
End Function
Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67
  • Please! **1.** don't post answers to incomplete questions / off-topic question as it just encourages more of them *(good guide is, has the OP shown effort to approach the problem themselves)*. **2.** source code examples for a different language *(and yes VB is different to VBScript)* it is confusing enough trying to keep them separate as it is. – user692942 Dec 14 '16 at 13:17
  • Will think about what you say - if you will think about being more inclusive. Half the reason I wrote that answer was in reaction to the flaming the OP got for being imprecise about his JSON example and then for his English. I thought I'd show him that there is a welcome here, whilst giving him a way forward and leaving him some problems to solve for himself. – Vanquished Wombat Dec 14 '16 at 15:25
  • It wasn't a flame they said they had a web service, then later said they didn't. You're making the wrong assumptions, the reason I mention that is because it is the difference between a question being on-topic and off-topic. If they don't have any code to show and everything is conceptual then they need to go away at least attempt something then come back when they have a specific problem. – user692942 Dec 14 '16 at 15:29
  • Actually by answering what you did was make the OP think it is ok to not provide a clear problem with reproducible code to a specific problem, not to mention that what you provided was a mishmash of VB and VBScript then give them the job of trying to decipher it. At this point I can't even see *( if they don't have a web service at present)* how they could even accept this answer without testing it. – user692942 Dec 14 '16 at 15:32
  • Why can they not ask a conceptual question? – Vanquished Wombat Dec 14 '16 at 16:45
  • Guys, I am more like a monitoring tools administrator with very little programming exposure. Since I knew such a request is coming my way from my boss, I thought it was best to start researching on the topic beforehand. Vanquished Wombat has shown me a way forward and I would probably take that as a starting point. Thanks for your support. – mitheun sunny Dec 14 '16 at 17:00
  • @VanquishedWombat that response alone tell's me your still missing the point. – user692942 Dec 14 '16 at 19:00
  • @VanquishedWombat the answer was accepted there is no need to try and delete it, if the question is eventually closed it will go then. You don't need to force the issue, just think in future when answering questions. – user692942 Dec 15 '16 at 22:10