Parsing JSON in AMX Mod X typically requires the amx_json include file, which is part of the AMX Mod X distribution.
Here's how you can parse the given JSON object:
pawn
#include <amxmodx>
#include <amx_json> // Essential for JSON parsing
// The JSON string you want to parse
new const g_szJsonString[] = "{ \"product\": \"Laptop\", \"price\": 1200.50, \"inStock\": true }";
public plugin_init()
{
// Plugin information
register_plugin("JSON Parser Example", "1.0", "YourName");
// Declare variables to store the parsed data
new product_name[64]; // Enough buffer for "Laptop" and potential longer names
new Float:product_price;
new product_inStock; // Boolean values are usually stored as integers (0 for false, 1 for true)
// Declare a JSON handle and an error code variable
new JSON_Handle:json_obj = INVALID_JSON_HANDLE;
new JSON_Error:error_code;
// --- 1. Parse the JSON string ---
server_print("Attempting to parse JSON string:");
server_print("%s", g_szJsonString);
json_obj = json_parse_string(g_szJsonString, error_code);
// --- 2. Check for parsing errors ---
if (error_code == JSON_ERROR_NONE)
{
server_print("JSON parsed successfully!");
// --- 3. Retrieve values by key ---
// Get "product" (string)
if (json_get_string(json_obj, "product", product_name, sizeof(product_name)))
{
server_print("Product: %s", product_name);
}
else
{
server_print("Error: Could not retrieve 'product'.");
}
// Get "price" (float)
if (json_get_float(json_obj, "price", product_price))
{
server_print("Price: %.2f", product_price); // Use %.2f to format with 2 decimal places
}
else
{
server_print("Error: Could not retrieve 'price'.");
}
// Get "inStock" (boolean)
if (json_get_bool(json_obj, "inStock", product_inStock))
{
server_print("In Stock: %s", product_inStock ? "Yes" : "No");
}
else
{
server_print("Error: Could not retrieve 'inStock'.");
}
}
else
{
// Parsing failed, print the error
server_print("JSON Parsing Error: %s", json_error_to_string(error_code));
}
// --- 4. Free the JSON handle ---
// It's crucial to free the handle to prevent memory leaks.
// This should be done whether parsing succeeded or not, as long as json_obj is not INVALID_JSON_HANDLE.
if (json_obj != INVALID_JSON_HANDLE)
{
json_free_handle(json_obj);
server_print("JSON handle freed.");
}
}
Explanation:
#include <amx_json>: This line brings in the necessary functions and definitions for JSON parsing. Make sure amx_json.inc is in your amxmodx/scripting/include directory.
g_szJsonString[]: Your JSON string. Notice that internal double quotes (") within the string need to be escaped with a backslash (\").
Variable Declaration:
product_name[64]: A character array to hold the "Laptop" string.
Float:product_price: A float variable to hold the 1200.50 value. AMXX uses Float: prefix for float variables.
product_inStock: An integer variable for the boolean true. In AMX Mod X, true is typically 1 and false is 0.
JSON_Handle:json_obj: This will hold a reference to the parsed JSON object. Initialize it to INVALID_JSON_HANDLE.
JSON_Error:error_code: This variable will store any error code returned by the parsing function.
json_parse_string(g_szJsonString, error_code): This is the core function. It attempts to parse the g_szJsonString.
If successful, it returns a JSON_Handle (which is assigned to json_obj) and sets error_code to JSON_ERROR_NONE.
If it fails, it returns INVALID_JSON_HANDLE and sets error_code to an appropriate error constant (e.g., JSON_ERROR_PARSE).
Error Checking (if (error_code == JSON_ERROR_NONE)): Always check the error_code to ensure parsing was successful before attempting to retrieve values. json_error_to_string() can convert the error code into a human-readable string.
Retrieving Values:
json_get_string(json_obj, "product", product_name, sizeof(product_name)): Retrieves the string associated with the key "product". It takes the JSON handle, the key name, the buffer to store the string, and the size of the buffer. It returns true on success, false on failure (e.g., key not found or wrong type).
json_get_float(json_obj, "price", product_price): Retrieves the float associated with the key "price".
To compile and run this:
Save the code as a .sma file (e.g., json_parser.sma) in amxmodx/scripting/.
Compile it using amxxpc.exe or by running compile.exe in the amxmodx/scripting/ directory.
The compiled .amxx file (e.g., json_parser.amxx) will be in amxmodx/plugins/.
Add json_parser.amxx to your amxmodx/configs/plugins.ini file.
Restart your game server. You will see the output in the server console.
json_get_bool(json_obj, "inStock", product_inStock): Retrieves the boolean associated with the key "inStock".
json_free_handle(json_obj): Crucial! After you are done with the JSON object, you must free its memory using this function. Failing to do so will lead to memory leaks on your server. It's good practice to call this regardless of whether the parsing succeeded, as long as json_obj holds a valid handle.