samp.directory
← Scripts y librerías

NimaBastani/pawn-json-parser

Pure Pawn JSON Parser for SA-MP/open.mp servers | Full-featured JSON parsing, building, and serialization WITHOUT any plugins

Librería★ 1actualizado abr 2026MITPawn
Abrir en GitHub

README.md

JSON Parser for SA-MP/open.mp (Pawn)

A comprehensive, pure-Pawn JSON parser, builder, serializer, and query engine for SA-MP/open.mp servers. No plugins required.

About This Project

This library has been a quiet side project of mine for roughly 2 years. I started it because I needed a reliable JSON solution for my SA-MP server and nothing out there felt right - either too limited, or required external plugins I didn't want to depend on.

So I built my own, piece by piece, version by version. It was never meant to be public. Just a personal tool I kept improving whenever I hit a new edge case or needed a feature that wasn't there yet (or if I had an exam the day after).

But at some point I looked at it and thought... why not share it? Maybe someone else is in the same spot I was. So here it is, nothing fancy, just a solid pure-Pawn JSON parser that does what it's supposed to do.


Table of Contents


Installation

  1. Copy json_parser.inc into your pawno/include/ directory.
  2. Include it in your script:
#include <json_parser>

No plugins, no external dependencies. Pure Pawn.


Configuration

All limits can be overridden before including the file using #define:

DefineDefaultDescription
JSON_MAX_NODES2048Maximum number of JSON nodes across all documents
JSON_MAX_KEY_LEN64Maximum length of a key string
JSON_MAX_VALUE_LEN256Maximum length of a value string
JSON_MAX_DEPTH32Maximum nesting depth during parsing
JSON_MAX_DOCUMENTS16Maximum number of simultaneous documents
JSON_MAX_STRING_LEN4096Maximum input JSON string length for parsing
JSON_SERIALIZE_BUFFER4096Internal buffer size for serialization output

Example override:

#define JSON_MAX_NODES 4096
#define JSON_MAX_STRING_LEN 8192
#include <json_parser>

Quick Start

Parsing JSON

new docId;
new jsonStr[] = "{\"name\":\"John\",\"age\":25,\"vip\":true}";

if (JSON_Parse(jsonStr, docId))
{
    new root = JSON_GetRootNode(docId);

    new name[32];
    JSON_GetStringByPath(root, "name", name);
    // name = "John"

    new age;
    JSON_GetIntByPath(root, "age", age);
    // age = 25

    new bool:vip;
    JSON_GetBoolByPath(root, "vip", vip);
    // vip = true

    JSON_DestroyDocument(docId);
}

Building JSON

new docId, root;
root = JSON_BuildObject(docId);

JSON_ObjectSetString(root, "server", "My SA-MP Server");
JSON_ObjectSetInt(root, "maxPlayers", 100);
JSON_ObjectSetBool(root, "active", true);

new output[512];
JSON_Prettify(root, output);
print(output);

JSON_DestroyDocument(docId);

Output:

{
  "server": "My SA-MP Server",
  "maxPlayers": 100,
  "active": true
}

Function Quick Reference

FunctionReturnsDescription
JSON_Init()1Initialize parser state
JSON_Cleanup()1Free all documents and reset state
JSON_CreateDocument()docIdCreate empty document
JSON_DestroyDocument(docId)0/1Destroy document and free nodes
JSON_GetRootNode(docId)nodeIdGet root node of document
JSON_Parse(str, &docId)0/1Parse JSON string
JSON_ParseFile(file, &docId)0/1Parse JSON file
JSON_Validate(str)boolCheck if string is valid JSON
JSON_GetErrorMessage(dest)-Get last parse error
JSON_GetNodeType(nodeId)typeGet node type constant
JSON_GetNodeTypeName(nodeId, dest)0/1Get type as string
JSON_GetNodeKey(nodeId, dest)0/1Get node key
JSON_GetChildCount(nodeId)countCount direct children
JSON_IsNull(nodeId)boolCheck if null
JSON_IsString(nodeId)boolCheck if string
JSON_IsInt(nodeId)boolCheck if integer
JSON_IsFloat(nodeId)boolCheck if float
JSON_IsBool(nodeId)boolCheck if boolean
JSON_IsObject(nodeId)boolCheck if object
JSON_IsArray(nodeId)boolCheck if array
JSON_IsNumber(nodeId)boolCheck if int or float
JSON_GetString(nodeId, dest)0/1Get string value
JSON_GetInt(nodeId, &val)0/1Get integer value
JSON_GetFloat(nodeId, &val)0/1Get float value
JSON_GetBool(nodeId, &val)0/1Get boolean value
JSON_GetParent(nodeId)nodeIdGet parent node
JSON_GetFirstChild(nodeId)nodeIdGet first child
JSON_GetLastChild(nodeId)nodeIdGet last child
JSON_GetNextSibling(nodeId)nodeIdGet next sibling
JSON_GetPrevSibling(nodeId)nodeIdGet previous sibling
JSON_GetObjectChild(nodeId, key)nodeIdFind child by key
JSON_ObjectHasKey(nodeId, key)boolCheck if key exists
JSON_GetArrayElement(nodeId, idx)nodeIdGet array element by index
JSON_GetArraySize(nodeId)countGet array length
JSON_GetByPath(nodeId, path)nodeIdNavigate by dot path
JSON_GetStringByPath(nodeId, path, dest)0/1Get string by path
JSON_GetIntByPath(nodeId, path, &val)0/1Get int by path
JSON_GetFloatByPath(nodeId, path, &val)0/1Get float by path
JSON_GetBoolByPath(nodeId, path, &val)0/1Get bool by path
JSON_SetByPath(docId, nodeId, path, val)0/1Set node by path
JSON_SetStringByPath(docId, nodeId, path, val)0/1Set string by path
JSON_SetIntByPath(docId, nodeId, path, val)0/1Set int by path
JSON_SetFloatByPath(docId, nodeId, path, val)0/1Set float by path
JSON_SetBoolByPath(docId, nodeId, path, val)0/1Set bool by path
JSON_RemoveByPath(nodeId, path)0/1Remove node by path
JSON_EnsurePath(docId, nodeId, path)nodeIdCreate intermediate path nodes
JSON_CreateObject(docId)nodeIdCreate empty object node
JSON_CreateArray(docId)nodeIdCreate empty array node
JSON_CreateString(docId, val)nodeIdCreate string node
JSON_CreateInt(docId, val)nodeIdCreate integer node
JSON_CreateFloat(docId, val)nodeIdCreate float node
JSON_CreateBool(docId, val)nodeIdCreate boolean node
JSON_CreateNull(docId)nodeIdCreate null node
JSON_ObjectSetValue(nodeId, key, valNode)0/1Set key-value on object
JSON_ObjectSetString(nodeId, key, val)0/1Set string on object
JSON_ObjectSetInt(nodeId, key, val)0/1Set int on object
JSON_ObjectSetFloat(nodeId, key, val)0/1Set float on object
JSON_ObjectSetBool(nodeId, key, val)0/1Set bool on object
JSON_ObjectSetNull(nodeId, key)0/1Set null on object
JSON_ObjectRemoveKey(nodeId, key)0/1Remove key from object
JSON_ArrayAppend(nodeId, valNode)0/1Append to array
JSON_ArrayAppendString(nodeId, docId, val)0/1Append string to array
JSON_ArrayAppendInt(nodeId, docId, val)0/1Append int to array
JSON_ArrayAppendFloat(nodeId, docId, val)0/1Append float to array
JSON_ArrayAppendBool(nodeId, docId, val)0/1Append bool to array
JSON_ArrayInsert(nodeId, idx, valNode)0/1Insert into array
JSON_ArrayRemove(nodeId, idx)0/1Remove from array
JSON_BuildObject(&docId)nodeIdCreate doc with root object
JSON_BuildArray(&docId)nodeIdCreate doc with root array
JSON_Serialize(nodeId, dest, maxlen, pretty)0/1Serialize to string
JSON_Minify(nodeId, dest)0/1Compact serialization
JSON_Prettify(nodeId, dest)0/1Pretty serialization
JSON_SerializeToFile(nodeId, file, pretty)0/1Serialize to file
JSON_SerializeDoc(docId, dest, maxlen, pretty)0/1Serialize document
JSON_SaveDocument(docId, file, pretty)0/1Save document to file
JSON_CloneNode(docId, nodeId)nodeIdDeep copy a node
JSON_MergeObjects(docId, target, source, overwrite)0/1Merge two objects
JSON_Equal(nodeA, nodeB)boolDeep equality check
JSON_FindByKey(nodeId, key)nodeIdSearch by key recursively
JSON_FindByStringValue(nodeId, val)nodeIdSearch by string value
JSON_FindByIntValue(nodeId, val)nodeIdSearch by int value
JSON_IterateObject(nodeId, prev)nodeIdManual object iteration
JSON_IterateArray(nodeId, prev)nodeIdManual array iteration
JSON_GetObjectKeys(nodeId, keys, max, maxlen)countExtract all keys
JSON_NodeToString(nodeId, dest)0/1Convert any value to string
JSON_NodeToInt(nodeId, &val)0/1Convert any value to int
JSON_NodeToFloat(nodeId, &val)0/1Convert any value to float
JSON_CountNodes(nodeId)countCount all nodes in subtree
JSON_GetMaxDepth(nodeId)depthGet max nesting depth
JSON_GetFreeNodeCount()countGet available node slots
JSON_DebugPrintNode(nodeId, depth)-Print debug tree to console

Core Concepts

Documents

A document is a container that owns a set of nodes. Every parsing or building operation starts with a document. Documents are identified by an integer ID.

  • Maximum simultaneous documents: JSON_MAX_DOCUMENTS (default 16)
  • Always destroy documents when done to free nodes

Nodes

Every JSON value (string, number, object, array, bool, null) is stored as a node. Nodes form a tree structure with parent-child and sibling relationships.

Each node has:

  • A type (object, array, string, int, float, bool, null)
  • A key (if it's a child of an object)
  • A value (for primitive types)
  • Links to parent, first child, last child, previous sibling, next sibling

Data Types

ConstantValueDescription
JSON_TYPE_NULL0JSON null
JSON_TYPE_STRING1String value
JSON_TYPE_INT2Integer value
JSON_TYPE_FLOAT3Float value
JSON_TYPE_BOOL4Boolean (true/false)
JSON_TYPE_OBJECT5JSON object {}
JSON_TYPE_ARRAY6JSON array []

API Reference

Initialization

JSON_Init()

Initializes the parser state. Called automatically by most functions. Safe to call multiple times.

JSON_Init();

Returns: 1 always.


Document Management

JSON_CreateDocument()

Creates a new empty document.

new docId = JSON_CreateDocument();
if (docId == JSON_INVALID_DOCUMENT)
{
    print("ERROR: No free document slots!");
}

Returns: Document ID on success, JSON_INVALID_DOCUMENT (-1) on failure.


JSON_DestroyDocument(docId)

Destroys a document and frees all its nodes.

JSON_DestroyDocument(docId);

Returns: 1 on success, 0 on failure.

Always call this when you're done with a document to prevent node leaks.


JSON_GetRootNode(docId)

Gets the root node of a document.

new root = JSON_GetRootNode(docId);
if (root == JSON_INVALID_NODE)
{
    print("Document has no root node");
}

Returns: Node ID or JSON_INVALID_NODE (-1).


Parsing

JSON_Parse(const jsonString[], &docId)

Parses a JSON string into a new document.

new docId;
new input[] = "{\"key\":\"value\",\"num\":42}";

if (JSON_Parse(input, docId))
{
    new root = JSON_GetRootNode(docId);
    // ... use the data ...
    JSON_DestroyDocument(docId);
}
else
{
    new errMsg[128];
    JSON_GetErrorMessage(errMsg);
    printf("Parse error: %s", errMsg);
}

Returns: 1 on success, 0 on failure.

Supported JSON features:

  • Objects, arrays, strings, integers, floats, booleans, null
  • Nested structures to JSON_MAX_DEPTH levels
  • Escape sequences in strings: \", \\, \/, \b, \f, \n, \r, \t
  • Negative numbers and decimal floats

JSON_ParseFile(const filename[], &docId)

Reads a file and parses its contents as JSON.

new docId;
if (JSON_ParseFile("scriptfiles/config.json", docId))
{
    new root = JSON_GetRootNode(docId);
    // ...
    JSON_DestroyDocument(docId);
}

Returns: 1 on success, 0 on failure.


Node Information

JSON_GetNodeType(nodeId)

Returns the type constant of a node.

new type = JSON_GetNodeType(nodeId);
if (type == JSON_TYPE_STRING)
{
    // handle string
}

Returns: One of JSON_TYPE_* constants, or -1 if invalid.


JSON_GetNodeTypeName(nodeId, dest[], maxlen = sizeof(dest))

Gets a human-readable type name.

new typeName[16];
JSON_GetNodeTypeName(nodeId, typeName);
printf("Type: %s", typeName);
// Output: "string", "int", "float", "bool", "null", "object", "array", or "unknown"

Returns: 1 on success, 0 on failure.


JSON_GetNodeKey(nodeId, dest[], maxlen = sizeof(dest))

Gets the key of a node (only meaningful for children of objects).

new key[64];
JSON_GetNodeKey(childNode, key);
printf("Key: %s", key);

Returns: 1 on success, 0 on failure.


JSON_GetChildCount(nodeId)

Returns the number of direct children of a node.

new count = JSON_GetChildCount(objectNode);
printf("Object has %d properties", count);

Returns: Child count, or 0 if invalid/no children.


Type Check Functions

All return bool:

JSON_IsNull(nodeId)      // true if JSON_TYPE_NULL
JSON_IsString(nodeId)    // true if JSON_TYPE_STRING
JSON_IsInt(nodeId)       // true if JSON_TYPE_INT
JSON_IsFloat(nodeId)     // true if JSON_TYPE_FLOAT
JSON_IsBool(nodeId)      // true if JSON_TYPE_BOOL
JSON_IsObject(nodeId)    // true if JSON_TYPE_OBJECT
JSON_IsArray(nodeId)     // true if JSON_TYPE_ARRAY
JSON_IsNumber(nodeId)    // true if JSON_TYPE_INT or JSON_TYPE_FLOAT

Example:

if (JSON_IsString(node))
{
    new val[128];
    JSON_GetString(node, val);
    printf("String value: %s", val);
}
else if (JSON_IsInt(node))
{
    new val;
    JSON_GetInt(node, val);
    printf("Int value: %d", val);
}

Value Getters

JSON_GetString(nodeId, dest[], maxlen = sizeof(dest))

Gets the string value of a node.

new value[128];
if (JSON_GetString(node, value))
{
    printf("Value: %s", value);
}

Returns: 1 on success, 0 on failure. Works on JSON_TYPE_STRING nodes.


JSON_GetInt(nodeId, &value)

Gets the integer value of a node.

new value;
if (JSON_GetInt(node, value))
{
    printf("Value: %d", value);
}

Returns: 1 on success, 0 on failure. Works on JSON_TYPE_INT nodes.


JSON_GetFloat(nodeId, &Float:value)

Gets the float value of a node.

new Float:value;
if (JSON_GetFloat(node, value))
{
    printf("Value: %f", value);
}

Returns: 1 on success, 0 on failure. Works on JSON_TYPE_FLOAT nodes.


JSON_GetBool(nodeId, &bool:value)

Gets the boolean value of a node.

new bool:value;
if (JSON_GetBool(node, value))
{
    printf("Value: %s", value ? "true" : "false");
}

Returns: 1 on success, 0 on failure. Works on JSON_TYPE_BOOL nodes.


Navigation

These functions let you traverse the node tree manually.

JSON_GetParent(nodeId)
new parent = JSON_GetParent(childNode);

Returns: Parent node ID, or JSON_INVALID_NODE.


JSON_GetFirstChild(nodeId)
new first = JSON_GetFirstChild(objectNode);

Returns: First child node ID, or JSON_INVALID_NODE.


JSON_GetLastChild(nodeId)
new last = JSON_GetLastChild(objectNode);

Returns: Last child node ID, or JSON_INVALID_NODE.


JSON_GetNextSibling(nodeId)
new next = JSON_GetNextSibling(currentNode);

Returns: Next sibling node ID, or JSON_INVALID_NODE.


JSON_GetPrevSibling(nodeId)
new prev = JSON_GetPrevSibling(currentNode);

Returns: Previous sibling node ID, or JSON_INVALID_NODE.


Object Lookup

JSON_GetObjectChild(objectNode, const key[])

Finds a direct child of an object by key name.

new nameNode = JSON_GetObjectChild(root, "name");
if (nameNode != JSON_INVALID_NODE)
{
    new name[32];
    JSON_GetString(nameNode, name);
}

Returns: Node ID or JSON_INVALID_NODE.


JSON_ObjectHasKey(objectNode, const key[])

Checks if an object contains a specific key.

if (JSON_ObjectHasKey(root, "email"))
{
    // key exists
}

Returns: bool.


Array Access

JSON_GetArrayElement(arrayNode, index)

Gets an array element by zero-based index.

new elem = JSON_GetArrayElement(arrayNode, 0); // first element
if (elem != JSON_INVALID_NODE)
{
    new val;
    JSON_GetInt(elem, val);
}

Returns: Node ID or JSON_INVALID_NODE.


JSON_GetArraySize(arrayNode)

Returns the number of elements in an array.

new size = JSON_GetArraySize(arrayNode

Leer el resto en GitHub

json-parseropenmp-libraryopenmp-serveropenmultiplayerpawnsa-mpsa-mp-librarysamp

Esta página se genera con lo que GitHub publica sobre el repositorio. samp.directory no aloja el código. Informar de un problema con esta ficha