Back to Home
Writing to a JSON Variable
Reading fields is only half the picture. When a command needs to
change a value, you update the field with $jsonSetString,
then save the whole variable back to storage with
$setVar using $jsonStringify to reassemble
it.
The pattern
Every write follows this three-step structure:
$jsonParse[$getVar[STATS;$authorID]]
$jsonSetString[field;NewValue]
$setVar[STATS;$jsonStringify;$authorID]
- Parse the variable to load it into memory.
- Update the field you want to change.
-
Save it back:
$jsonStringifyreassembles the full object and$setVarwrites it to storage.
Editing multiple fields at once
You can call $jsonSetString multiple times before saving.
Only one $setVar is needed at the end:
$jsonParse[$getVar[STATS;$authorID]]
$jsonSetString[cash;NewCashValue]
$jsonSetString[xp;NewXpValue]
$setVar[STATS;$jsonStringify;$authorID]
Example 1: Add cash to a user's balance
$nomention
$jsonParse[$getVar[STATS;$authorID]]
$jsonSetString[cash;$calculate[$json[cash]+100]]
$setVar[STATS;$jsonStringify;$authorID]
You received 100 coins. Balance: $json[cash]
What happens:
$jsonParseloads the variable.-
$jsonSetString[cash;...]setscashto current cash plus 100 using$calculate. -
$setVar[$jsonStringify]saves the updated object. -
$json[cash]reads the updated value still held in memory for the output line.
Example 2: Deduct cash and update XP at once
$nomention
$jsonParse[$getVar[STATS;$authorID]]
$onlyIf[$json[cash]>=50;You need at least 50 coins.]
$jsonSetString[cash;$calculate[$json[cash]-50]]
$jsonSetString[xp;$calculate[$json[xp]+10]]
$setVar[STATS;$jsonStringify;$authorID]
You spent 50 coins and gained 10 XP.
What happens:
$jsonParseloads the variable.-
$onlyIfchecks the user has enough cash before doing anything. $jsonSetString[cash;...]subtracts 50 from cash.$jsonSetString[xp;...]adds 10 to xp.-
One
$setVar[$jsonStringify]saves both changes at once.
Common uses
- Any command that changes a value: cash, xp, level, item counts
- Initialising fields: set a field to a default if it is missing before the command runs
- Chained edits: update several fields in one command with a single save at the end
See also
- Setting up: how to design and initialise the variable
- Reading values: how to read fields before editing them