pawn
#include <amxmodx>
#include <string>
public plugin_init() {
register_plugin("JSON Parser Example", "1.0", "Author")
// The JSON string to parse
new jsonString[] = "{\"product\":\"Laptop\",\"price\":1200.50,\"inStock\":true}"
// Parse and display results
parse_json(jsonString)
}
parse_json(const json[]) {
new product[32]
new Float:price
new bool:inStock
// Extract product
new productKey[] = "\"product\":\""
new productPos = containi(json, productKey)
if (productPos != -1) {
productPos += strlen(productKey)
new i = 0
while (json[productPos + i] != '"' && i < charsmax(product)) {
product[i] = json[productPos + i]
i++
}
product[i] = 0 // Null-terminate
}
// Extract price
new priceKey[] = "\"price\":"
new pricePos = containi(json, priceKey)
if (pricePos != -1) {
pricePos += strlen(priceKey)
new priceStr[16]
new i = 0
while (json[pricePos + i] != ',' && json[pricePos + i] != '}' && i < charsmax(priceStr)) {
priceStr[i] = json[pricePos + i]
i++
}
priceStr[i] = 0 // Null-terminate
price = str_to_float(priceStr)
}
// Extract inStock
new stockKey[] = "\"inStock\":"
new stockPos = containi(json, stockKey)
if (stockPos != -1) {
stockPos += strlen(stockKey)
new stockStr[8]
new i = 0
while (json[stockPos + i] != ',' && json[stockPos + i] != '}' && i < charsmax(stockStr)) {
stockStr[i] = json[stockPos + i]
i++
}
stockStr[i] = 0 // Null-terminate
inStock = equal(stockStr, "true")
}
// Display results
server_print("Product: %s", product)
server_print("Price: %.2f", price)
server_print("In Stock: %s", inStock ? "Yes" : "No")
}