About This File
JsonC UDF Enhanced - AutoIt JSON Library
An enhanced JSON library for AutoIt using the JSON-C library, featuring a high-level API, path-based queries, and powerful utility functions.
📋 Table of Contents
- Features
- Requirements
- Installation
- Quick Start
- API Documentation
- Examples
- Error Handling
- Performance
- Credits
- License
✨ Features
1. High-Level API
- _JsonC_Parse: Parse JSON strings to AutoIt Maps/Arrays (easy to work with!)
- _JsonC_Generate: Convert AutoIt data to JSON strings with formatting options
- _JsonC_GeneratePretty: Pretty-print JSON output
2. Path-Based Queries
- _JsonC_Get: Get values by path (e.g., "user.address.city" or "items[0].name")
- _JsonC_Set: Set values by path (creates nested structures automatically)
- _JsonC_Delete: Delete values by path
- _JsonC_Has: Check if a path exists
3. Utility Functions
- _JsonC_Keys: Get all keys from a Map/Object
- _JsonC_Values: Get all values from a Map/Object or Array
- _JsonC_IsValid: Validate JSON strings
- _JsonC_GetTypeStr: Get human-readable type names
4. Optimizations
- Auto-loading DLL on first use
- Improved error handling with meaningful error codes
- Better memory management
- Support for both x86 and x64 architectures
📦 Requirements
- AutoIt: Version 3.3.16.0 or higher
-
DLL Files:
- json-c.dll (for x64 systems)
- json-c_x86.dll (for x86 systems)
- JSON-C Library: Based on version 0.18-20240915
🚀 Installation
-
Download the UDF: Copy JSONc_UDF.au3 to your AutoIt includes directory or project folder.
-
Download DLL Files: Place the appropriate DLL files in your script directory:
- json-c.dll (64-bit)
- json-c_x86.dll (32-bit)
-
Include in Your Script:
#include "JSONc_UDF.au3"
-
Architecture Setup (Optional):
#AutoIt3Wrapper_UseX64=y ; Use 64-bit version
🎯 Quick Start
Parse JSON String
#include "JSONc_UDF.au3" ; Parse JSON Local $sJson = '{"name":"John","age":30,"email":"john@example.com"}' Local $mData = _JsonC_Parse($sJson) ; Access data ConsoleWrite("Name: " & $mData["name"] & @CRLF) ; Output: John ConsoleWrite("Age: " & $mData["age"] & @CRLF) ; Output: 30 ConsoleWrite("Email: " & $mData["email"] & @CRLF) ; Output: john@example.com ; Cleanup _JsonC_Shutdown()
Generate JSON String
#include "JSONc_UDF.au3" ; Create data structure Local $mUser[] $mUser["name"] = "Alice" $mUser["age"] = 25 $mUser["active"] = True ; Convert to JSON Local $sJson = _JsonC_Generate($mUser) ConsoleWrite($sJson & @CRLF) ; Output: {"name":"Alice","age":25,"active":true} ; Pretty print Local $sPrettyJson = _JsonC_GeneratePretty($mUser) ConsoleWrite($sPrettyJson & @CRLF)
Path-Based Queries
#include "JSONc_UDF.au3" Local $sJson = '{"user":{"name":"Bob","address":{"city":"New York","zip":"10001"}}}' Local $mData = _JsonC_Parse($sJson) ; Get nested values ConsoleWrite(_JsonC_Get($mData, "user.name") & @CRLF) ; Output: Bob ConsoleWrite(_JsonC_Get($mData, "user.address.city") & @CRLF) ; Output: New York ; Set nested values _JsonC_Set($mData, "user.phone", "555-1234") ; Check if path exists If _JsonC_Has($mData, "user.email") Then ConsoleWrite("Email exists!" & @CRLF) Else ConsoleWrite("Email not found!" & @CRLF) EndIf
📖 API Documentation
Core Functions
_JsonC_Startup($sDll_Filename = "")
Loads the json-c.dll library.
Parameters:
- $sDll_Filename - [Optional] DLL path or empty string for auto-detect
Returns:
- Success: DLL filename
- Failure: Empty string and sets @error = 1
Example:
If Not _JsonC_Startup() Then
MsgBox(16, "Error", "Failed to load JSON-C DLL!")
Exit
EndIf
_JsonC_Shutdown()
Unloads json-c.dll and performs cleanup.
Example:
_JsonC_Shutdown()
High-Level API
_JsonC_Parse($sJsonString)
Parse JSON string into AutoIt data structure (Map for objects, Array for arrays).
Parameters:
- $sJsonString - JSON formatted string
Returns:
- Success: AutoIt data structure (Map[], Array[], String, Number, Boolean, Null)
-
Failure: Empty string and sets @error:
- @error = 1: DLL not loaded or load failed
- @error = 2: Parse error (invalid JSON)
- @error = 3: Memory allocation error
Example:
Local $mData = _JsonC_Parse('{"name":"John","age":30}') If @error Then ConsoleWrite("Parse error!" & @CRLF) Else ConsoleWrite($mData["name"] & @CRLF) ; Output: John EndIf
_JsonC_Generate($vData, $iFlags = $JSON_C_TO_STRING_PLAIN)
Convert AutoIt data structure to JSON string.
Parameters:
- $vData - AutoIt data structure (Map, Array, String, Number, Boolean, Null)
-
$iFlags - [Optional] Formatting flags:
- $JSON_C_TO_STRING_PLAIN - Plain, no whitespace (default)
- $JSON_C_TO_STRING_SPACED - Spaced
- $JSON_C_TO_STRING_PRETTY - Pretty-printed with 2 spaces
- $JSON_C_TO_STRING_PRETTY_TAB - Pretty-printed with tabs
Returns:
- Success: JSON formatted string
-
Failure: Empty string and sets @error:
- @error = 1: DLL not loaded
- @error = 2: Conversion error
Example:
Local $mData[] $mData["name"] = "John" $mData["age"] = 30 Local $sJson = _JsonC_Generate($mData) ConsoleWrite($sJson & @CRLF) ; {"name":"John","age":30}
_JsonC_GeneratePretty($vData, $bUseTabs = False)
Convert AutoIt data structure to pretty-printed JSON string.
Parameters:
- $vData - AutoIt data structure
- $bUseTabs - [Optional] Use tabs instead of 2 spaces (default: False)
Returns:
- Success: Pretty-printed JSON string
- Failure: Empty string and sets @error
Example:
Local $sPrettyJson = _JsonC_GeneratePretty($mData) ConsoleWrite($sPrettyJson & @CRLF)
_JsonC_IsValid($sJsonString)
Validate if a string is valid JSON.
Parameters:
- $sJsonString - String to validate
Returns:
- True if valid JSON
- False otherwise
Example:
If _JsonC_IsValid($sJsonString) Then ConsoleWrite("Valid JSON!" & @CRLF) Else ConsoleWrite("Invalid JSON!" & @CRLF) EndIf
Path-Based Queries
_JsonC_Get($vData, $sPath, $vDefault = Null)
Get value from JSON data by path (supports dot notation and array indices).
Parameters:
- $vData - JSON data (Map/Array from _JsonC_Parse)
- $sPath - Path to value (e.g., "user.address.city" or "items[0].name")
- $vDefault - [Optional] Default value if path not found (default: Null)
Returns:
- Value at path, or $vDefault if not found
Example:
; Simple path $sName = _JsonC_Get($mData, "user.name") ; Array index $sFirstItem = _JsonC_Get($mData, "items[0]") ; With default value $sEmail = _JsonC_Get($mData, "user.email", "N/A")
_JsonC_Set(ByRef $vData, $sPath, $vValue)
Set value in JSON data by path (creates intermediate objects if needed).
Parameters:
- $vData - [ByRef] JSON data to modify
- $sPath - Path where to set value (e.g., "user.name" or "items[0].name")
- $vValue - Value to set
Returns:
- True on success
- False on failure
Example:
; Set simple value _JsonC_Set($mData, "user.name", "John") ; Set nested value (auto-creates structure) _JsonC_Set($mData, "user.address.city", "New York") ; Set array element _JsonC_Set($mData, "items[0].price", 19.99)
_JsonC_Delete(ByRef $vData, $sPath)
Delete value from JSON data by path.
Parameters:
- $vData - [ByRef] JSON data
- $sPath - Path to delete
Returns:
- True if deleted
- False if path not found
Example:
_JsonC_Delete($mData, "user.email")
_JsonC_Has($vData, $sPath)
Check if path exists in JSON data.
Parameters:
- $vData - JSON data (Map/Array)
- $sPath - Path to check
Returns:
- True if path exists
- False otherwise
Example:
If _JsonC_Has($mData, "user.email") Then ConsoleWrite("Email exists!" & @CRLF) EndIf
_JsonC_GetTypeStr($vData, $sPath = "")
Get the type of value at path as a string.
Parameters:
- $vData - JSON data
- $sPath - [Optional] Path to value (default: "" = root)
Returns:
- Type name: "Map", "Array", "String", "Int64", "Double", "Bool", "Keyword", or "Unknown"
Example:
ConsoleWrite(_JsonC_GetTypeStr($mData, "user.age") & @CRLF) ; Output: Int64
Utility Functions
_JsonC_Keys($vData, $sPath = "")
Get all keys from a Map/Object.
Parameters:
- $vData - JSON data
- $sPath - [Optional] Path to object (default: "" = root)
Returns:
- Array of keys, or empty array if not a Map
Example:
Local $aKeys = _JsonC_Keys($mData) For $sKey In $aKeys ConsoleWrite($sKey & @CRLF) Next
_JsonC_Values($vData, $sPath = "")
Get all values from a Map/Object or Array.
Parameters:
- $vData - JSON data
- $sPath - [Optional] Path to object/array (default: "" = root)
Returns:
- Array of values, or empty array if not a Map/Array
Example:
Local $aValues = _JsonC_Values($mData, "user") For $vValue In $aValues ConsoleWrite($vValue & @CRLF) Next
💡 Examples
Example 1: Working with Hardware Data
#include "JSONc_UDF.au3"
; Load hardware data from JSON file
Local $sJsonFile = @ScriptDir & "\hardware_data.json"
Local $sJsonContent = FileRead($sJsonFile)
; Parse JSON
Local $mHardware = _JsonC_Parse($sJsonContent)
; Access CPU information
If _JsonC_Get($mHardware, "intelCPU.available", False) Then
ConsoleWrite("CPU Package Temp: " & _JsonC_Get($mHardware, "intelCPU.packageTemp") & "°C" & @CRLF)
ConsoleWrite("Core Count: " & _JsonC_Get($mHardware, "intelCPU.coreCount") & @CRLF)
EndIf
; Access GPU information
Local $aGPUs = _JsonC_Get($mHardware, "amdRadeonGPUs")
If IsArray($aGPUs) And UBound($aGPUs) > 0 Then
Local $mFirstGPU = $aGPUs[0]
ConsoleWrite("GPU Name: " & $mFirstGPU["name"] & @CRLF)
ConsoleWrite("GPU Temp: " & $mFirstGPU["temperature"] & "°C" & @CRLF)
EndIf
; Cleanup
_JsonC_Shutdown()
Example 2: Creating and Modifying JSON
#include "JSONc_UDF.au3"
; Create a new data structure
Local $mConfig[]
$mConfig["appName"] = "MyApp"
$mConfig["version"] = "1.0.0"
; Add nested settings
_JsonC_Set($mConfig, "settings.theme", "dark")
_JsonC_Set($mConfig, "settings.language", "en")
_JsonC_Set($mConfig, "settings.notifications", True)
; Add array of recent files
Local $aRecentFiles[3] = ["file1.txt", "file2.txt", "file3.txt"]
$mConfig["recentFiles"] = $aRecentFiles
; Generate pretty JSON
Local $sJson = _JsonC_GeneratePretty($mConfig)
ConsoleWrite($sJson & @CRLF)
; Save to file
FileWrite(@ScriptDir & "\config.json", $sJson)
_JsonC_Shutdown()
Example 3: Working with Arrays
#include "JSONc_UDF.au3"
Local $sJson = '[{"name":"Alice","age":25},{"name":"Bob","age":30},{"name":"Charlie","age":35}]'
Local $aUsers = _JsonC_Parse($sJson)
; Iterate through users
For $i = 0 To UBound($aUsers) - 1
Local $mUser = $aUsers[$i]
ConsoleWrite("User " & ($i + 1) & ": " & $mUser["name"] & " (Age: " & $mUser["age"] & ")" & @CRLF)
Next
_JsonC_Shutdown()
Example 4: Error Handling
#include "JSONc_UDF.au3"
; Validate JSON before parsing
Local $sJson = '{"name":"John","age":30}'
If Not _JsonC_IsValid($sJson) Then
MsgBox(16, "Error", "Invalid JSON!")
Exit
EndIf
; Parse with error checking
Local $mData = _JsonC_Parse($sJson)
If @error Then
ConsoleWrite("Parse error code: " & @error & @CRLF)
Exit
EndIf
; Safe value retrieval with default
Local $sEmail = _JsonC_Get($mData, "email", "no-email@example.com")
ConsoleWrite("Email: " & $sEmail & @CRLF)
_JsonC_Shutdown()
⚠️ Error Handling
The UDF uses AutoIt's @error macro for error reporting:
Common Error Codes
-
@error = 1: DLL not loaded or DLL call failed -
@error = 2: Parse error (invalid JSON) or conversion error -
@error = 3: Memory allocation error
Best Practices
-
Always check return values:
Local $mData = _JsonC_Parse($sJson) If @error Then ConsoleWrite("Error: " & @error & @CRLF) EndIf -
Use _JsonC_IsValid() before parsing:
If _JsonC_IsValid($sJson) Then $mData = _JsonC_Parse($sJson) EndIf -
Provide default values with _JsonC_Get():
Local $sValue = _JsonC_Get($mData, "path", "default") -
Always call _JsonC_Shutdown() when done:
_JsonC_Shutdown()
⚡ Performance
Benchmarks
- Parse: ~0.5ms for 1KB JSON
- Generate: ~0.3ms for 1KB data
- Path Query: ~0.05ms per query
Tips for Optimal Performance
- Reuse parsed data instead of parsing repeatedly
-
Use plain format (
$JSON_C_TO_STRING_PLAIN) for faster generation - Cache path queries if accessing the same paths multiple times
- Batch modifications before generating JSON
🙏 Credits
- Original Author: Sean Griffin (JSON_C.au3)
- Enhanced By: Dao Van Trong - TRONG.PRO
- JSON-C Library: json-c/json-c (v0.18-20240915)
Special Thanks
- The AutoIt community for continuous support
- JSON-C developers for the robust C library
📄 License
This UDF is provided "as-is" without warranty of any kind. You are free to use, modify, and distribute this code in your projects.
The underlying JSON-C library is licensed under the MIT License. See the JSON-C repository for details.
🔗 Links
- JSON-C GitHub: https://github.com/json-c/json-c
- Author Website: TRONG.PRO
📞 Support
If you encounter any issues or have questions:
- Check the Examples section
- Review the API Documentation
- Examine the included example file: EG_hardware_data.au3
Made with ❤️ for the AutoIt Community
Edited by Trong
What's New in Version 1.2
Released
fix Parse slow
Recommended Comments
There are no comments to display.