Skip to content

cJson API Reference

Core Concepts

VB Type and JSON Correspondence

VB TypeJSON TypeDescription
Dictionary{ "key": "value" } objectKey-value structure
Collection[ 1, 2, 3 ] arrayOrdered list

Core Member Functions

MemberPrimary PurposeDescription
NewItemCreate child object nodeCreates a Dictionary-type child node, corresponding to JSON object {...}
NewItemsCreate child array nodeCreates a Collection-type child node, corresponding to JSON array [...]
ItemSet/read object membersSet/get key-value pairs on the current node (Dictionary)
ItemsSet/read array membersSet/get array elements on the current node (Collection)
RootChained readingReturns root node Object, supports chained access

Correct JSON Construction Flow

vb
'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 With

Properties

Public Properties

PropertyTypeDescription
RootObjectDefault member, returns root node object (Dictionary/Collection), most commonly used
SelfcJsonReturns the object's own instance (Me), for scenarios requiring passing this object
RootTextStringThe JSON text from the last encode/decode operation
RootItemDictionaryRoot node dictionary object, corresponding to JSON object { ... }
RootItemsCollectionRoot node collection object, corresponding to JSON array [ ... ]
LastErrorStringLast error message
WhiteSpaceSetVariantGlobal indent settings

Type Correspondence:

  • Dictionary → JSON object { "key": "value" } (key-value pairs)
  • Collection → JSON array [ 1, 2, 3 ] (ordered list)

Status Properties

LastSuccess

vb
Public Property Get LastSuccess() As Boolean

Returns whether the last operation was successful (True when LastError = "").

Example:

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

Root (Default Member, for Chained Read/Write)

vb
Public Property Get Root() As Object
Attribute Root.VB_UserMemId = 0

Returns the root node object. If RootItems.Count > 0 returns Collection (array), otherwise returns Dictionary (object).

Important Features:

  • Default Member: Root is the class's default member, allowing direct access with Json("key"), equivalent to Json.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 Root when reading nested JSON data, supports unlimited levels of chained access
  • Type Correspondence:
    • Dictionary → JSON object { "key": "value" }
    • Collection → JSON array [ 1, 2, 3 ]

Example:

vb
'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")
Next

RootIsEmpty

vb
Public Property Get RootIsEmpty() As Boolean

Checks whether the root node is empty (no key-value pairs and no array elements).

Example:

vb
If Json.RootIsEmpty Then
    MsgBox "JSON object is empty"
End If

RootIsArray

vb
Public Property Get RootIsArray() As Boolean

Checks whether the root node is of array type.

Example:

vb
If Json.RootIsArray Then
    MsgBox "Root node is an array"
End If

Data Access Properties

Item (Add/Modify Members on Current Object Node)

vb
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:

  1. Set key-value pairs on root node (root node defaults to object)
  2. Set key-value pairs on child objects created by NewItem

Example:

vb
'===== 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.Root

Items (Add/Modify Members on Current Array Node)

vb
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:

  1. Add elements on child arrays created by NewItems

Example:

vb
'===== 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

vb
Public Sub Clear()

Clear all data and reset object state.

Example:

vb
Json.Item("name") = "John"
Json.Clear
'Now Json.RootIsEmpty = True

NewItem (Create Child Object Node)

vb
Public Function NewItem(Optional ParentKey As String) As cJson

Creates 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 Item to 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:

  1. Call NewItem([Key]) to create child object
  2. Use Item on the returned cJson instance to set key-value pairs

Example:

vb
'===== 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 With

NewItems (Create Child Array Node)

vb
Public Function NewItems(Optional ParentKey As String) As cJson

Creates 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 Items to add elements on the child array, or use NewItem to 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:

  1. Call NewItems([Key]) to create child array
  2. On the returned cJson instance:
    • Use Items(0) to add plain value elements
    • Use NewItem() to add object elements

Example:

vb
'===== 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 With

Encode

vb
Public Function Encode( _
    Optional Obj As Variant, _
    Optional Whitespace As Variant, _
    Optional FromUnicode As Boolean _
) As String

Encodes 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:

vb
'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

vb
Public Function Decode(ByRef Source As Variant) As cJson

Parses 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 instance
    • ADODB.Recordset - Automatically convert to JSON array
    • cCollection - Extract underlying Collection or Dictionary
    • Collection - Directly use as JSON array root node
    • Dictionary - 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:

vb
'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

vb
Public Function LoadFrom(ByVal Path As String, _
    Optional CharSet As String = "UTF-8" _
) As cJson

Loads JSON data from a file.

Parameters:

  • Path - File path
  • CharSet - Character encoding (default UTF-8)

Returns:

  • Returns self instance (supports chained calling)

Example:

vb
'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

vb
Public Function SaveTo( _
    ByVal FileName As String, _
    Optional CharSet As String = "UTF-8", _
    Optional Whitespace As Variant, _
    Optional FromUnicode As Boolean _
) As String

Saves JSON data to a file.

Parameters:

  • FileName - File path
  • CharSet - Character encoding (default UTF-8)
  • Whitespace - Format indent
  • FromUnicode - Whether to display Chinese characters

Returns:

  • Saved JSON string content

Example:

vb
'Simple save
Json.SaveTo "C:\data.json"

'Formatted save
Json.SaveTo "C:\data.json", "UTF-8", 2, True

ToArray

vb
Public Function ToArray() As Variant

Converts JSON data to a VB array.

Example:

vb
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

vb
'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

vb
'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").Count

Loop Through Array

vb
'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")
Next

Type Conversion Notes

vb
'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"))

VB6 and LOGO copyright of Microsoft Corporation