API Specstable
4 min read time
Documentation
JSON
Parse and serialize JSON data for storage, API communication, and data interchange.
apijsondataparsing
JSON Parsing
JavaScript Object Notation (JSON) is the standard format for data interchange in PixelScript. Use JSON to store data, communicate with APIs, and serialize complex objects.
Converting to JSON
Serialize to JSON with JSON.stringify(value)
Converts a JavaScript value to a JSON string.
const playerData = { name: "Notch", level: 50, coins: 1000, inventory: ["diamond_sword", "golden_apple"] }; const json = JSON.stringify(playerData); log(json); // Output: {"name":"Notch","level": 50,"coins":1000,"inventory":["diamond_sword","golden_apple"]}
Parsing JSON
Parse JSON with JSON.parse(jsonString)
Converts a JSON string into a JavaScript object.
const jsonString = '{"name":"Notch","level":50,"coins": 1000}'; const playerData = JSON.parse(jsonString); log(playerData.name); // Output: Notch log(playerData. level); // Output: 50 log(playerData.coins); // Output: 1000
Practical Examples
Saving player data
function savePlayerData(player) { const data = { uuid: player.getUniqueId().toString(), name: player.getName(), level: player.getLevel(), health: player.getHealth(), location: { world: player.getWorld().getName(), x: player.getLocation().getX(), y: player.getLocation().getY(), z: player.getLocation().getZ() } }; const json = JSON.stringify(data); // Save to database Sql.makeUpdate( "UPDATE player_data SET data = ? WHERE uuid = ?", (stmt) => { stmt.setString(1, json); stmt.setString(2, data.uuid); }, (rows) => { log("Saved player data for", data.name); } ); }
Loading player data
function loadPlayerData(playerUUID, callback) { Sql.makeQuery( "SELECT data FROM player_data WHERE uuid = ?", (stmt) => { stmt.setString(1, playerUUID); }, (rs) => { if (rs !== null && rs.next()) { const jsonString = rs.getString("data"); const playerData = JSON.parse(jsonString); callback(playerData); } else { callback(null); } } ); } // Usage loadPlayerData(player.getUniqueId().toString(), (data) => { if (data) { log("Loaded data for", data. name); log("Level:", data.level); } else { log("No data found"); } });
API communication
// Sending JSON to an API Scheduler.runAsync(() => { const payload = { server: "PSCraft", event: "player_join", player: playerName, timestamp: Date.now() }; const response = fetch("https://api.example.com/events", { method: "POST", headers: { "Content-Type": "application/json" }, postBody: JSON.stringify(payload) }); if (response.isSuccessful()) { const result = JSON.parse(response.asString()); log("API response:", result. message); } });
Configuration files
// Save configuration const config = { spawnLocation: { world: "world", x: 0, y: 64, z: 0 }, welcomeMessage: "Welcome to PSCraft! ", maxPlayers: 100, enablePvP: false }; const configJson = JSON.stringify(config); // Write to file system or database // Load configuration const loadedConfig = JSON.parse(configJson); log("Spawn world:", loadedConfig.spawnLocation.world); log("Welcome message:", loadedConfig. welcomeMessage);
Cloning objects
// Deep clone an object using JSON const original = { name: "Notch", stats: { level: 50, xp: 10000 } }; const clone = JSON.parse(JSON. stringify(original)); clone.stats.level = 51; log(original.stats.level); // Output: 50 (unchanged) log(clone.stats.level); // Output: 51 (modified)
Error Handling
Always wrap JSON.parse() in try-catch blocks to handle invalid JSON:
const jsonString = '{"invalid json}'; try { const data = JSON.parse(jsonString); log("Parsed successfully:", data); } catch (e) { error("Failed to parse JSON:", e.message); }
Supported Data Types
JSON supports the following JavaScript types:
Supported:
- Strings:
"hello" - Numbers:
42,3.14 - Booleans:
true,false - Arrays:
[1, 2, 3] - Objects:
{"key": "value"} - null:
null
Not Supported:
- Functions
- undefined
- Symbols
- Dates (convert to ISO string first)
- Java objects (extract properties first)
// Converting unsupported types const data = { name: "Notch", joinDate: new Date().toISOString(), // Convert Date to string location: { x: player.getLocation().getX(), // Extract from Java object y: player.getLocation().getY(), z: player.getLocation().getZ() } }; const json = JSON.stringify(data);
Best Practices
DO:
- Always validate JSON before parsing
- Use try-catch when parsing untrusted JSON
- Convert Java objects to plain JavaScript objects before serializing
- Store structured data as JSON in databases
DON'T:
- Store functions in JSON (they won't serialize)
- Parse user input without validation
- Serialize circular references (will throw an error)
- Forget to handle parsing errors
- Store sensitive data in plain JSON without encryption
Previous
Console Logging
Log messages, warnings, and errors to the server console for debugging and monitoring.
Next
import/export
Share code between scripts using ES6-style named imports and exports.
Documentation in early stages. Not meant for public consumption.