cJson API Reference
Core Concepts
VB Type and JSON Correspondence
| VB Type | JSON Type | Description |
|---|---|---|
| Dictionary | { "key": "value" } object | Key-value structure |
| Collection | [ 1, 2, 3 ] array | Ordered list |
Core Member Functions
| Member | Primary Purpose | Description |
|---|---|---|
| NewItem | Create child object node | Creates a Dictionary-type child node, corresponding to JSON object {...} |
| NewItems | Create child array node | Creates a Collection-type child node, corresponding to JSON array [...] |
| Item | Set/read object members | Set/get key-value pairs on the current node (Dictionary) |
| Items | Set/read array members | Set/get array elements on the current node (Collection) |
| Root | Chained reading | Returns root node Object, supports chained access |
Correct JSON Construction Flow
'1. Create root node (itself is an object node)
With New cJson
'Set key-value pairs on root node using Item
.Item("name") = "John"
.Item("age") = 25
'2. Create child array node (using NewItems)
With .NewItems("hobbies") 'Create child array named "hobbies"
'Add elements on child array using Items
.Items(0) = "Reading" 'Index=0 means append
.Items(0) = "Coding"
End With
'3. Create child object node (using NewItem)
With .NewItem("address") 'Create child object named "address"
'Set key-value pairs on child object using Item
.Item("city") = "Beijing"
.Item("zip") = "100000"
End With
'4. Encode to JSON string
Dim JsonString As String
JsonString = .Encode()
'Output: {"name":"John","age":25,"hobbies":["Reading","Coding"],"address":{"city":"Beijing","zip":"100000"}}
End WithProperties
Public Properties
| Property | Type | Description |
|---|---|---|
Root | Object | Default member, returns root node object (Dictionary/Collection), most commonly used |
Self | cJson | Returns the object's own instance (Me), for scenarios requiring passing this object |
RootText | String | The JSON text from the last encode/decode operation |
RootItem | Dictionary | Root node dictionary object, corresponding to JSON object { ... } |
RootItems | Collection | Root node collection object, corresponding to JSON array [ ... ] |
LastError | String | Last error message |
WhiteSpaceSet | Variant | Global indent settings |
Type Correspondence:
- Dictionary → JSON object
{ "key": "value" }(key-value pairs) - Collection → JSON array
[ 1, 2, 3 ](ordered list)
Status Properties
LastSuccess
Public Property Get LastSuccess() As BooleanReturns whether the last operation was successful (True when LastError = "").
Example:
Json.Decode JsonText
If Json.LastSuccess Then
MsgBox "Parse successful"
Else
MsgBox "Parse failed: " & Json.LastError
End IfRoot (Default Member, for Chained Read/Write)
Public Property Get Root() As Object
Attribute Root.VB_UserMemId = 0Returns the root node object. If RootItems.Count > 0 returns Collection (array), otherwise returns Dictionary (object).
Important Features:
- Default Member:
Rootis the class's default member, allowing direct access withJson("key"), equivalent toJson.Root("key") - Returns Object: Returns Dictionary (corresponding to JSON object
{...}) or Collection (corresponding to JSON array[...]), supports chained nested access - For Chained Read/Write: Recommended to use
Rootwhen reading nested JSON data, supports unlimited levels of chained access - Type Correspondence:
- Dictionary → JSON object
{ "key": "value" } - Collection → JSON array
[ 1, 2, 3 ]
- Dictionary → JSON object
Example:
'Direct access (using default member feature)
MsgBox Json("name") 'Equivalent to Json.Root("name")
MsgBox Json("user")("name") 'Chained access to nested object
MsgBox Json("items")(1)("title") 'Access object within array (array index starts from 1)
'Explicitly using Root property
MsgBox Json.Root("name")
MsgBox Json.Root("user")("name")
'Iterate through array
Dim Item As Variant
For Each Item In Json("data")
Debug.Print Item("name")
NextRootIsEmpty
Public Property Get RootIsEmpty() As BooleanChecks whether the root node is empty (no key-value pairs and no array elements).
Example:
If Json.RootIsEmpty Then
MsgBox "JSON object is empty"
End IfRootIsArray
Public Property Get RootIsArray() As BooleanChecks whether the root node is of array type.
Example:
If Json.RootIsArray Then
MsgBox "Root node is an array"
End IfData Access Properties
Item (Add/Modify Members on Current Object Node)
Public Property Get Item(ByVal Key As String) As Variant
Public Property Let Item(ByVal Key As String, Dat As Variant)
Public Property Set Item(ByVal Key As String, Dat As Variant)Access or set key-value pairs on the current object node (Dictionary).
Core Purpose:
- Add/Modify Object Members: Set key-value pairs on the current object node, for building JSON object properties
- Applicable Node: Only usable on Dictionary-type nodes (including root node and child objects created by NewItem)
- JSON Correspondence: Operates on Dictionary, corresponding to JSON object
{ "key": "value" }
Parameters:
Key- Key name (string)Dat- Value to set (any type)
Usage Scenarios:
- Set key-value pairs on root node (root node defaults to object)
- Set key-value pairs on child objects created by NewItem
Example:
'===== Scenario 1: Set key-value pairs on root node =====
With New cJson
'Root node itself is an object, use Item directly
.Item("name") = "John"
.Item("age") = 25
.Item("active") = True
'Result: { "name": "John", "age": 25, "active": true }
End With
'===== Scenario 2: Set on child object created by NewItem =====
With New cJson
'Create child object "address"
With .NewItem("address")
'Set key-value pairs on child object using Item
.Item("city") = "Beijing"
.Item("zip") = "100000"
End With
'Result: { "address": { "city": "Beijing", "zip": "100000" } }
End With
'===== Reading Values (Recommended: use Root for chained access) =====
'Not recommended: Item returns Variant, does not support chained access
Name = Json.Item("name")
'Recommended: Root returns Object, supports chained access
Name = Json.Root("name")
City = Json.Root("address")("city") 'Chained access to nested object
'Set object reference
Dim SubJson As New cJson
Set Json.Item("sub") = SubJson.RootItems (Add/Modify Members on Current Array Node)
Public Property Get Items(ByVal Index As Long) As Variant
Public Property Let Items(ByVal Index As Long, Dat As Variant)
Public Property Set Items(ByVal Index As Long, Dat As Variant)Access or set array elements on the current array node (Collection). Note: Index starts from 1.
Core Purpose:
- Add/Modify Array Members: Add or modify array elements on the current array node
- Applicable Node: Only usable on Collection-type nodes (child arrays created by NewItems)
- JSON Correspondence: Operates on Collection, corresponding to JSON array
[ 1, 2, 3 ]
Parameters:
Index- Array index (starts from 1)Dat- Value to set
Special Usage:
- When
Index = 0, it means append a new element to the end of the array
Usage Scenarios:
- Add elements on child arrays created by NewItems
Example:
'===== Scenario: Add elements on child array created by NewItems =====
With New cJson
With .NewItems("tags") 'Create child array named "tags"
'Add elements on child array using Items
.Items(0) = "VIP" 'Index=0 means append
.Items(0) = "Active"
.Items(0) = "Paid"
End With
'Result: { "tags": ["VIP", "Active", "Paid"] }
'Object elements in array
With .NewItems("users")
With .NewItem() 'First object element in array
.Item("name") = "John"
.Item("age") = 25
End With
With .NewItem() 'Second object element in array
.Item("name") = "Jane"
.Item("age") = 30
End With
End With
'Result: { "users": [{"name":"John","age":25}, {"name":"Jane","age":30}] }
End With
'===== Access Array Elements (using Root, starting from 1) =====
Dim First As String
First = Json.Root("tags")(1) 'VIP
'Modify array element
Json.Root("tags").Items(1) = "New value"
'Iterate through array (recommended: use Root)
Dim Item As Variant
For Each Item In Json.Root("tags")
Debug.Print Item
Next
'Modify array element
Json.Items(1) = "New value"Methods
Clear
Public Sub Clear()Clear all data and reset object state.
Example:
Json.Item("name") = "John"
Json.Clear
'Now Json.RootIsEmpty = TrueNewItem (Create Child Object Node)
Public Function NewItem(Optional ParentKey As String) As cJsonCreates a new Dictionary-type child node, corresponding to JSON object { ... }.
Core Purpose:
- Create Child Object: Creates a child object (Dictionary) node under the current node
- JSON Correspondence: Creates a JSON object
{ "key": "value" } - Follow-up Operations: After creation, use
Itemto set key-value pairs on the child object
Parameters:
ParentKey- Key name in parent node (optional)- With key name: child object is mounted under this key in the parent node
- Without key name: child object is added to the parent node's array (parent node must be array type)
Returns:
- Newly created cJson instance (Dictionary type)
Usage Flow:
- Call
NewItem([Key])to create child object - Use
Itemon the returned cJson instance to set key-value pairs
Example:
'===== Scenario 1: Create named child object (with ParentKey) =====
With New cJson
'Create child object named "address"
With .NewItem("address")
'Set key-value pairs on child object using Item
.Item("city") = "Beijing"
.Item("zip") = "100000"
End With
'Result: { "address": { "city": "Beijing", "zip": "100000" } }
End With
'===== Scenario 2: Create object element in array (omit ParentKey) =====
With New cJson
With .NewItems("users") 'First create array "users"
With .NewItem() 'Create first object element in array
.Item("name") = "John"
.Item("age") = 25
End With
With .NewItem() 'Create second object element in array
.Item("name") = "Jane"
.Item("age") = 30
End With
End With
'Result: { "users": [{"name":"John","age":25}, {"name":"Jane","age":30}] }
End With
'===== Scenario 3: Unlimited Level Nesting =====
With New cJson
With .NewItem("level1")
With .NewItem("level2")
With .NewItem("level3")
.Item("value") = "Deep data"
End With
End With
End With
'Result: { "level1": { "level2": { "level3": { "value": "Deep data" } } } }
End WithNewItems (Create Child Array Node)
Public Function NewItems(Optional ParentKey As String) As cJsonCreates a new Collection-type child node, corresponding to JSON array [ ... ].
Core Purpose:
- Create Child Array: Creates a child array (Collection) node under the current node
- JSON Correspondence: Creates a JSON array
[ 1, 2, 3 ] - Follow-up Operations: After creation, use
Itemsto add elements on the child array, or useNewItemto add object elements
Parameters:
ParentKey- Key name in parent node (optional)- With key name: child array is mounted under this key in the parent node
- Without key name: child array is added to the parent node's array (parent node must be array type)
Returns:
- Newly created cJson instance (Collection type)
Usage Flow:
- Call
NewItems([Key])to create child array - On the returned cJson instance:
- Use
Items(0)to add plain value elements - Use
NewItem()to add object elements
- Use
Example:
'===== Scenario 1: Create named child array (with ParentKey) =====
With New cJson
'Create child array named "tags"
With .NewItems("tags")
'Add elements on child array using Items
.Items(0) = "VIP" 'Index=0 means append
.Items(0) = "Active"
.Items(0) = "Paid"
End With
'Result: { "tags": ["VIP", "Active", "Paid"] }
End With
'===== Scenario 2: Create array within array (omit ParentKey) =====
With New cJson
With .NewItems("matrix") 'Create two-dimensional array
With .NewItems() 'First row array
.Items(0) = 1
.Items(0) = 2
End With
With .NewItems() 'Second row array
.Items(0) = 3
.Items(0) = 4
End With
End With
'Result: { "matrix": [[1, 2], [3, 4]] }
End With
'===== Scenario 3: Object Array (Mixed use of NewItem and Items) =====
With New cJson
With .NewItems("users")
'Array element is object: use NewItem to create, use Item to set
With .NewItem()
.Item("name") = "John"
.Item("age") = 25
End With
'Add another object
With .NewItem()
.Item("name") = "Jane"
.Item("age") = 30
End With
End With
'Result: { "users": [{"name":"John","age":25}, {"name":"Jane","age":30}] }
End WithEncode
Public Function Encode( _
Optional Obj As Variant, _
Optional Whitespace As Variant, _
Optional FromUnicode As Boolean _
) As StringEncodes an object to a JSON string.
Parameters:
Obj- Object to encode (optional, uses internal RootItem/RootItems when omitted)Whitespace- Format indent (number for spaces, string for indent characters)FromUnicode- Whether to decode Unicode encoding to Chinese characters (True displays Chinese)
Returns:
- JSON string
Example:
'Simple encoding
Dim JsonStr As String
JsonStr = Json.Encode()
'Formatted output (2-space indent)
JsonStr = Json.Encode(, 2)
'Formatted and display Chinese
JsonStr = Json.Encode(, 2, True)
'Encode specified object
JsonStr = Json.Encode(Json.Item("subObject"), 2, True)Decode
Public Function Decode(ByRef Source As Variant) As cJsonParses JSON data into an object. Supports JSONP format, var variable format, and direct conversion from multiple object types.
Parameters:
Source- Data source to parse, supports the following types:String- JSON string (standard JSON / JSONP / var format)cJson- Copy data from another cJson instanceADODB.Recordset- Automatically convert to JSON arraycCollection- Extract underlying Collection or DictionaryCollection- Directly use as JSON array root nodeDictionary- Directly use as JSON object root node
Returns:
- Returns self instance (supports chained calling)
Supported Formats:
- Standard JSON:
{"name": "value"} - JSON Array:
[{"name": "value"}] - JSONP:
callback({"name": "value"}); - Var variable:
var data = {"name": "value"};
Example:
'Standard JSON
Json.Decode "{""name"":""John""}"
'JSONP format (auto-extracted)
Json.Decode "callback({""name"":""John""});"
'Var format (auto-extracted)
Json.Decode "var data = {""name"":""John""};"
'Copy from another cJson instance
Json.Decode AnotherJsonObj
'Convert from Recordset
Json.Decode Rs
'Chained calling
MsgBox Json.Decode(JsonText).Item("name")LoadFrom
Public Function LoadFrom(ByVal Path As String, _
Optional CharSet As String = "UTF-8" _
) As cJsonLoads JSON data from a file.
Parameters:
Path- File pathCharSet- Character encoding (default UTF-8)
Returns:
- Returns self instance (supports chained calling)
Example:
'Load from file
Json.LoadFrom "C:\data.json"
'Specify encoding
Json.LoadFrom "C:\data.json", "GB2312"
'Chained calling
MsgBox Json.LoadFrom("C:\data.json").Item("name")SaveTo
Public Function SaveTo( _
ByVal FileName As String, _
Optional CharSet As String = "UTF-8", _
Optional Whitespace As Variant, _
Optional FromUnicode As Boolean _
) As StringSaves JSON data to a file.
Parameters:
FileName- File pathCharSet- Character encoding (default UTF-8)Whitespace- Format indentFromUnicode- Whether to display Chinese characters
Returns:
- Saved JSON string content
Example:
'Simple save
Json.SaveTo "C:\data.json"
'Formatted save
Json.SaveTo "C:\data.json", "UTF-8", 2, TrueToArray
Public Function ToArray() As VariantConverts JSON data to a VB array.
Example:
Dim Arr As Variant
Arr = Json.ToArray()Internal Functions (Private)
The following functions are for internal use and are not publicly exposed:
ConvertToJson
Internal use, converts VB objects to JSON strings (from VBA-JSON).
ParseJson
Internal use, parses JSON strings into VB objects (from VBA-JSON).
Usage Tips
Chained Access to Deep Data
'Multi-level nested access
MsgBox Json.Item("level1")("level2")("level3")
'Array access (index starts from 1)
MsgBox Json.Item("users")(1)("name")Safe Value Retrieval
'Check if key exists (using RootItem)
If Json.RootItem.Exists("key") Then
Value = Json.Item("key")
End If
'Get array length
Dim Count As Long
Count = Json.Item("array").CountLoop Through Array
'For Each iteration
Dim Item As Variant
For Each Item In Json.Item("data")
Debug.Print Item("name")
Next
'For loop iteration (index starts from 1)
Dim i As Long
For i = 1 To Json.Item("data").Count
Debug.Print Json.Item("data")(i)("name")
NextType Conversion Notes
'Number to string
Dim StrValue As String
StrValue = CStr(Json.Item("numberField"))
'String to number
Dim NumValue As Long
NumValue = CLng(Json.Item("stringField"))
'Date handling
Dim DateValue As Date
DateValue = CDate(Json.Item("dateField"))