Quantcast
Viewing all articles
Browse latest Browse all 1449

simple json w/MSScript control

simple example of using the msscript control to parse json

9.23 - updated with xiaoyao's recommendation of default property get with let support
added enumProps, getType, isArray, stringify, beautify, (internal JSON and beautify scripts)

Code:

Public code
Public message

Private Sub Form_Load()
   
    Dim js As New CJSON
    Dim c As New Collection, x
   
    Const j1 = "{""code"":1,""message"":""this is my message""}"
   
    If Not js.Initilized() Then
        Debug.Print "Could not create script engine instance?"
        Exit Sub
    End If
   
    If Not js.LoadJson(j1) Then
        Debug.Print "Failed to load json 1"
        Exit Sub
    End If
   
    Debug.Print "code exists? " & js.exists("code")
   
    Set c = js.enumProps()
    Debug.Print "json fields:"
   
    For Each x In c
        Debug.Print vbTab & x & " (" & js.getType(x) & ") = " & js(x)
    Next
       
    js("code") = 21
    js("message") = "'new messge set from vb'" 'make sure to wrap strings in quotes

    'public object var names must match json names
    js.GetObjFields Me, "code,message"
    Debug.Print "me.code: " & Me.code
    Debug.Print "me.message: " & Me.message
   
   
'    {
'      "menu": {
'            "id": "file",
'            "value": "File",
'            "popup": {
'              "menuitem": [
'                {"value": "New"},
'                {"value": "Open"},
'                {"value": "Close"}
'              ]
'            }
'      }
'    }

    If Not js.LoadJson(Text1) Then
        Debug.Print "Failed to load text1 json"
        Exit Sub
    End If
   
    Dim sz As Long, i As Long
   
    Debug.Print "isArray(menu.popup.menuitem) = " & js.isArray("menu.popup.menuitem")
    Debug.Print "menu.popup.menuitem.length exists? " & js.exists("menu.popup.menuitem.length")
   
    sz = js("menu.popup.menuitem.length")
    For i = 0 To sz - 1
        Debug.Print "menuitem[" & i & "] = " & js("menu.popup.menuitem[" & i & "].value")
    Next
   
    x = js.stringify("menu.popup")
    Debug.Print "stringify(menu.popup) = " & x
    Debug.Print "Pretty: " & vbCrLf & js.beautify(x) & vbCrLf
   
    If js.parse(x) Then
        Debug.Print "menuitem[0].value = '" & js("menuitem[0].value") & "'"
    End If
   
    End
   
End Sub

Attached Files
  • Image may be NSFW.
    Clik here to view.
    File Type: zip
    cjson.zip (34.6 KB)

Viewing all articles
Browse latest Browse all 1449

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>