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.clsTo use it in your project, add a reference to the VBMAN library:
'Standard reference method
Dim Json As New VBMANLIB.cJson
'Or use the VBMAN global instance
With VBMAN.Json
'...
End WithQ2: 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.
'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 2Q3: How to clear a cJson instance?
A: Use the Clear method:
Json.Clear 'Clear all dataNote: When using the VBMAN.Json global instance, it's recommended to call Clear first:
With VBMAN.Json
.Clear 'Clean previous data
.Item("key") = "value"
End WithUsage Questions
Q4: How to check if JSON parsing was successful?
A: Use the LastSuccess property:
Json.Decode JsonText
If Json.LastSuccess Then
MsgBox "Parse successful"
Else
MsgBox "Parse failed: " & Json.LastError
End IfQ5: How to check if a key exists?
A: Use the RootItem.Exists method to check, use Root to access:
If Json.RootItem.Exists("key") Then
MsgBox Json.Root("key")
Else
MsgBox "Key does not exist"
End IfQ6: How to iterate through a JSON array?
A: Use Root to access the array, two iteration methods:
'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")
NextQ7: How to handle nested objects?
A: Use Root for chained access or layered access:
'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:
Json.Encode(, 2, True) 'Third parameter True means display Chinese as-isQ9: How to format JSON string output?
A: Set the second parameter of Encode:
Json.Encode(, 2) 'Use 2-space indent
Json.Encode(, 4) 'Use 4-space indent
Json.Encode(, vbTab) 'Use Tab indentQ10: How to handle special characters?
A: cJson automatically handles special character escaping:
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:
'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:
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 ChineseQ13: What character encodings are supported?
A: Common character encodings are supported:
UTF-8(recommended)UTF-16GB2312GBKASCII
HTTP Related Questions
Q14: How to send JSON data?
A: Construct a JSON string and send it:
'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 WithQ15: How to parse JSON returned by an API?
A: Use the ReturnJson method:
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 WithQ16: How to handle JSONP format?
A: cJson's Decode method automatically handles JSONP format:
'The following formats can all be auto-parsed
Json.Decode "callback({""name"":""John""});"
Json.Decode "var data = {""name"":""John""};"
Json.Decode "{""name"":""John""}" 'Standard JSONError Handling
Q17: What are common errors?
A: Common errors and solutions:
| Error | Cause | Solution |
|---|---|---|
| Index out of bounds | Accessing non-existent array index | Check array length before access |
| Key not found | Accessing non-existent key | Use Exists method to check |
| Type mismatch | Data type doesn't match variable | Use type conversion functions |
| Parse failure | Invalid JSON format | Check input string format |
Q18: How to debug JSON issues?
A: Use these debugging techniques:
'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:
- Use compact format for transmission:
Json.Encode()(no formatting) - Avoid deep nested object lookups
- Release unused objects promptly
- Consider batch processing for large data volumes
Q20: What's the difference between global and new instances?
A:
| Feature | VBMAN.Json (Global) | New cJson (New Instance) |
|---|---|---|
| Lifecycle | Application lifetime | Released with code block end |
| Data Sharing | Globally shared | Independent isolation |
| Use Case | Cache global config | Temporary data processing |
| Note | Need manual Clear | Auto cleanup |
Advanced Questions
Q21: How to construct JSON with array root node?
A: First call NewItem or NewItems:
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 WithQ22: How to merge two JSON objects?
A: Manually copy key-value pairs:
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 SubQ23: How to copy a JSON object?
A: Encode then decode:
Dim Copy As New cJson
Copy.Decode Original.Encode()Q24: What's the difference between Root and Item?
A:
| Feature | Root | Item |
|---|---|---|
| Default Member | Yes (can use Json("key")) | No |
| Return Type | Object (Dictionary/Collection) | Variant |
| Chained Access | Supported | Limited support |
| Primary Use | Reading data | Setting values |
| Example | Json.Root("a")("b") | Json.Item("a") = 1 |
Recommended Usage:
'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:
Json.Item("created") = Format(Now(), "yyyy-mm-dd HH:mm:ss")