VBMAN.Json - JSON Operation Object
Overview
VBMAN.Json provides JSON data parsing and generation functionality, supporting nested objects, arrays, and is the preferred solution for handling JSON data in VB6.
Core Features
- Bidirectional Conversion: Supports JSON string parsing and object encoding
- Nested Support: Unlimited level nested objects and arrays
- Type Safety: Automatic data type conversion handling
- Formatted Output: Supports indentation beautification output
- Chain Building: Fluent JSON building API
Properties
| Property | Type | Description |
|---|---|---|
Root | cJson | Root node object |
Item(key) | Variant | Access value of specified key (default member) |
Methods
Encode
Encode object to JSON string
vb
Public Function Encode(Optional obj As Object, Optional Indent As Integer = 0, Optional UseDoubleQuotes As Boolean = True) As StringParameters:
obj- Object to encode (default uses Root)Indent- Indentation spaces (0=no line breaks)UseDoubleQuotes- Use double quotes (default True)
Example:
vb
' Simple encoding
Dim json As New cJson
json("name") = "Zhang San"
json("age") = 25
Dim jsonStr As String
jsonStr = json.Encode()
' Result: {"name":"Zhang San","age":25}
' Formatted output
Dim prettyJson As String
prettyJson = json.Encode(, 2, True)
' Result:
' {
' "name": "Zhang San",
' "age": 25
' }Decode
Parse JSON string
vb
Public Function Decode(jsonString As String) As cJsonExample:
vb
' Parse JSON
Dim jsonStr As String
jsonStr = "{""name"":""Zhang San"",""age"":25}"
Dim json As cJson
Set json = VBMAN.Json.Decode(jsonStr)
Debug.Print json("name") ' Zhang San
Debug.Print json("age") ' 25Item
Access or set value
vb
' Read
Dim value As Variant
value = json("key")
' Write
json("key") = "value"
json("number") = 123
json("bool") = TrueNewItem / NewItems
Create nested object/array
vb
Public Function NewItem() As cJson
Public Function NewItems(key As String) As cJsonExample:
vb
' Create nested object
Dim user As New cJson
user("id") = 1
user("name") = "Zhang San"
With user.NewItem("address")
.Item("city") = "Beijing"
.Item("zip") = "100000"
End With
' Create array
Dim users As New cJson
With users.NewItems("data")
With .NewItem()
.Item("name") = "Zhang San"
.Item("age") = 25
End With
With .NewItem()
.Item("name") = "Li Si"
.Item("age") = 30
End With
End With
Debug.Print users.Encode(, 2)
' Result:
' {
' "data": [
' {"name":"Zhang San","age":25},
' {"name":"Li Si","age":30}
' ]
' }Exists
Check if key exists
vb
Public Function Exists(key As String) As BooleanExample:
vb
If json.Exists("email") Then
Debug.Print json("email")
Else
Debug.Print "email does not exist"
End IfRemove
Delete key
vb
Public Sub Remove(key As String)Comprehensive Examples
Example 1: Build Complex JSON
vb
Private Sub BuildComplexJson()
Dim root As New cJson
' Basic info
root("status") = "success"
root("message") = "Operation successful"
root("timestamp") = Format(Now, "yyyy-MM-ddThh:mm:ss")
' User data array
With root.NewItems("users")
' First user
With .NewItem()
.Item("id") = 1
.Item("name") = "Zhang San"
.Item("email") = "zhangsan@example.com"
' Nested address
With .NewItem("address")
.Item("province") = "Beijing"
.Item("city") = "Beijing City"
.Item("detail") = "Chaoyang District xxx Street"
End With
' Nested orders array
With .NewItems("orders")
With .NewItem()
.Item("order_id") = "ORD001"
.Item("amount") = 199.99
End With
With .NewItem()
.Item("order_id") = "ORD002"
.Item("amount") = 299.99
End With
End With
End With
' Second user
With .NewItem()
.Item("id") = 2
.Item("name") = "Li Si"
.Item("email") = "lisi@example.com"
End With
End With
' Pagination info
With root.NewItem("pagination")
.Item("page") = 1
.Item("page_size") = 20
.Item("total") = 100
End With
' Output JSON
Dim jsonStr As String
jsonStr = root.Encode(, 2, True)
Debug.Print jsonStr
End SubExample 2: Parse API Response
vb
Private Sub ParseApiResponse(response As String)
Dim json As cJson
Set json = VBMAN.Json.Decode(response)
' Check status
If json("status") = "success" Then
' Get user array
Dim users As cJson
Set users = json("data")("users")
' Iterate users
Dim i As Integer
For i = 0 To users.Count - 1
Dim user As cJson
Set user = users(i)
Debug.Print "ID: " & user("id")
Debug.Print "Name: " & user("name")
Debug.Print "Email: " & user("email")
' Check if address exists
If user.Exists("address") Then
Debug.Print "City: " & user("address")("city")
End If
Debug.Print "---"
Next i
' Get pagination info
Debug.Print "Total: " & json("data")("pagination")("total")
Else
Debug.Print "Error: " & json("message")
End If
End SubExample 3: Usage in Real Projects (from demos)
vb
' Build JSON response
Public Sub Json(ctx As cHttpServerContext)
Dim ID As Long: ID = ctx.Request.QueryString("id")
With New cJson
.Item("id") = ID
.Item("face") = ChrW(&H263A)
.Item("timestamp") = Now
.Item("status") = "success"
ctx.Response.Json .Root
End With
End Sub
' Parse request data
Public Sub HandleRequest(ctx As cHttpServerContext)
Dim requestData As String
requestData = ctx.Request.Body
Dim json As cJson
Set json = VBMAN.Json.Decode(requestData)
Dim username As String
Dim password As String
username = json("username")
password = json("password")
' Process login...
End SubExample 4: Database Record to JSON
vb
Private Sub RecordsetToJson(rs As ADODB.Recordset)
Dim root As New cJson
' Add metadata
root("count") = rs.RecordCount
root("timestamp") = Now
' Add data array
With root.NewItems("data")
Do While Not rs.EOF
With .NewItem()
Dim i As Integer
For i = 0 To rs.Fields.Count - 1
.Item(rs.Fields(i).Name) = rs.Fields(i).Value
Next i
End With
rs.MoveNext
Loop
End With
' Output
Debug.Print root.Encode(, 2)
End SubExample 5: INI Config to JSON
vb
Private Sub IniToJson()
VBMAN.Ini.LoadFrom App.Path & "\\config.ini"
Dim json As New cJson
' Convert all Sections
Dim sectionKey As Variant
For Each sectionKey In VBMAN.Ini.Root.Keys
With json.NewItem(CStr(sectionKey))
Dim key As Variant
For Each key In VBMAN.Ini.Root(sectionKey).Keys
.Item(key) = VBMAN.Ini.Root(sectionKey)(key)
Next key
End With
Next sectionKey
' Save as JSON file
VBMAN.FileEx.SetBufferText(json.Encode(, 2), "UTF-8").SaveData App.Path & "\\config.json"
End SubBest Practices
- Use Parameters: When building JSON, try to use NewItem/NewItems
- Check Existence: Use Exists to check if key exists before reading
- Error Handling: Add error handling when parsing JSON
- Type Attention: VB6 is weakly typed, note the difference between numbers and strings
- Formatted Output: Use indentation formatting for easier reading during debugging