Skip to content

cJson Frequently Asked Questions (FAQ)

Basic Questions

Q1: Where is the cJson class defined?

A: The cJson class is defined in the VBMAN library, located at:

vbman/src/Tools/Json/cJson.cls

To use it in your project, add a reference to the VBMAN library:

vb
'Standard reference method
Dim Json As New VBMANLIB.cJson

'Or use the VBMAN global instance
With VBMAN.Json
    '...
End With

Q2: Why do array indices start from 1 instead of 0?

A: cJson internally uses VB's Collection object to store arrays, and VB's Collection indexing starts from 1. This follows VB developer conventions.

vb
'Add elements using 0 (means append)
Json.Items(0) = "Element 1"
Json.Items(0) = "Element 2"

'Access using 1-based index (via Root)
MsgBox Json.Root("items")(1)  'Element 1
MsgBox Json.Root("items")(2)  'Element 2

Q3: How to clear a cJson instance?

A: Use the Clear method:

vb
Json.Clear  'Clear all data

Note: When using the VBMAN.Json global instance, it's recommended to call Clear first:

vb
With VBMAN.Json
    .Clear  'Clean previous data
    .Item("key") = "value"
End With

Usage Questions

Q4: How to check if JSON parsing was successful?

A: Use the LastSuccess property:

vb
Json.Decode JsonText
If Json.LastSuccess Then
    MsgBox "Parse successful"
Else
    MsgBox "Parse failed: " & Json.LastError
End If

Q5: How to check if a key exists?

A: Use the RootItem.Exists method to check, use Root to access:

vb
If Json.RootItem.Exists("key") Then
    MsgBox Json.Root("key")
Else
    MsgBox "Key does not exist"
End If

Q6: How to iterate through a JSON array?

A: Use Root to access the array, two iteration methods:

vb
'Method 1: For Each (recommended)
Dim Item As Variant
For Each Item In Json.Root("data")
    Debug.Print Item("name")
Next

'Method 2: For loop (index starts from 1)
Dim i As Long
For i = 1 To Json.Root("data").Count
    Debug.Print Json.Root("data")(i)("name")
Next

Q7: How to handle nested objects?

A: Use Root for chained access or layered access:

vb
'Chained access (recommended)
MsgBox Json.Root("level1")("level2")("level3")

'Or use default member feature (more concise)
MsgBox Json("level1")("level2")("level3")

'Layered access (recommended for deep nesting)
Dim Level1 As Object
Dim Level2 As Object
Set Level1 = Json.Root("level1")
Set Level2 = Level1("level2")
MsgBox Level2("level3")

Encoding Issues

Q8: How to display Chinese characters instead of Unicode?

A: Set the third parameter of Encode to True:

vb
Json.Encode(, 2, True)  'Third parameter True means display Chinese as-is

Q9: How to format JSON string output?

A: Set the second parameter of Encode:

vb
Json.Encode(, 2)     'Use 2-space indent
Json.Encode(, 4)     'Use 4-space indent
Json.Encode(, vbTab) 'Use Tab indent

Q10: How to handle special characters?

A: cJson automatically handles special character escaping:

vb
Json.Item("text") = "Text with \"quotes\" and \\backslashes"
'Output: "text": "Text with \"quotes\" and \\backslashes"

File Operation Questions

Q11: How to load JSON from a file?

A: Use the LoadFrom method:

vb
'Standard method
With New cJson
    .LoadFrom "C:\data.json"
    MsgBox .Item("name")
End With

'Chained calling
MsgBox VBMAN.Json.LoadFrom("C:\data.json")("name")

Q12: How to save JSON to a file?

A: Use the SaveTo method:

vb
Json.SaveTo "C:\data.json"                    'Simple save
Json.SaveTo "C:\data.json", "UTF-8"          'Specify encoding
Json.SaveTo "C:\data.json", "UTF-8", 2, True 'Formatted and display Chinese

Q13: What character encodings are supported?

A: Common character encodings are supported:

  • UTF-8 (recommended)
  • UTF-16
  • GB2312
  • GBK
  • ASCII

Q14: How to send JSON data?

A: Construct a JSON string and send it:

vb
'Construct request body
Dim Body As String
With New cJson
    .Item("key") = "value"
    Body = .Encode()
End With

'Send POST request
With New cHttpClient
    .SetRequestContentType JsonString
    .SendPost "https://api.example.com", Body
End With

Q15: How to parse JSON returned by an API?

A: Use the ReturnJson method:

vb
With VBMAN.HttpClient.Fetch(ReqGet, "https://api.example.com").ReturnJson()
    'Formatted display
    Text1.Text = .Encode(, 2, True)

    'Extract data
    If .Item("code") = 200 Then
        MsgBox .Item("data")("name")
    End If
End With

Q16: How to handle JSONP format?

A: cJson's Decode method automatically handles JSONP format:

vb
'The following formats can all be auto-parsed
Json.Decode "callback({""name"":""John""});"
Json.Decode "var data = {""name"":""John""};"
Json.Decode "{""name"":""John""}"  'Standard JSON

Error Handling

Q17: What are common errors?

A: Common errors and solutions:

ErrorCauseSolution
Index out of boundsAccessing non-existent array indexCheck array length before access
Key not foundAccessing non-existent keyUse Exists method to check
Type mismatchData type doesn't match variableUse type conversion functions
Parse failureInvalid JSON formatCheck input string format

Q18: How to debug JSON issues?

A: Use these debugging techniques:

vb
'1. Formatted output to view structure
Debug.Print Json.Encode(, 2, True)

'2. Check error information
Json.Decode BadJsonText
If Not Json.LastSuccess Then
    Debug.Print "Error: " & Json.LastError
End If

'3. Check data type
Debug.Print TypeName(Json.Item("field"))

Performance Questions

Q19: Tips for handling large data volumes?

A:

  1. Use compact format for transmission: Json.Encode() (no formatting)
  2. Avoid deep nested object lookups
  3. Release unused objects promptly
  4. Consider batch processing for large data volumes

Q20: What's the difference between global and new instances?

A:

FeatureVBMAN.Json (Global)New cJson (New Instance)
LifecycleApplication lifetimeReleased with code block end
Data SharingGlobally sharedIndependent isolation
Use CaseCache global configTemporary data processing
NoteNeed manual ClearAuto cleanup

Advanced Questions

Q21: How to construct JSON with array root node?

A: First call NewItem or NewItems:

vb
With New cJson
    'Root is an array
    With .NewItem()
        .Item("name") = "John"
    End With
    With .NewItem()
        .Item("name") = "Jane"
    End With

    'Result: [{"name": "John"}, {"name": "Jane"}]
    Debug.Print .Encode(, 2, True)
End With

Q22: How to merge two JSON objects?

A: Manually copy key-value pairs:

vb
Private Sub MergeJson(Target As cJson, Source As cJson)
    Dim Key As Variant
    For Each Key In Source.RootItem.Keys
        Target.Item(Key) = Source.Item(Key)
    Next
End Sub

Q23: How to copy a JSON object?

A: Encode then decode:

vb
Dim Copy As New cJson
Copy.Decode Original.Encode()

Q24: What's the difference between Root and Item?

A:

FeatureRootItem
Default MemberYes (can use Json("key"))No
Return TypeObject (Dictionary/Collection)Variant
Chained AccessSupportedLimited support
Primary UseReading dataSetting values
ExampleJson.Root("a")("b")Json.Item("a") = 1

Recommended Usage:

vb
'Set values with Item
Json.Item("name") = "John"

'Read values with Root
MsgBox Json.Root("name")
MsgBox Json.Root("address")("city")  'Chained access to nested object

'Shorthand form (using Root as default member)
MsgBox Json("name")
MsgBox Json("address")("city")

Q25: How to handle date types?

A: Dates are converted to strings; it's recommended to format them:

vb
Json.Item("created") = Format(Now(), "yyyy-mm-dd HH:mm:ss")

VB6 and LOGO copyright of Microsoft Corporation