SaveJsonAtomic ( json,file$[,indent] )
Parameters
|
json - JSON handle to save file$ - destination path indent (optional) - spaces per nesting level: 0: compact single-line output 1 to 8: pretty-printed with that many spaces; 2 (default) |
Description
|
Serializes a JSON document and atomically publishes it as a UTF-8 file. This is the save command for save files. "Atomic" is what protects your players: the document is serialized completely first, written to a hidden sibling file in the same directory, flushed, closed, and only then published over the destination with write-through semantics. A crash, power cut or full disk mid-save can never leave a half-written or truncated save behind - anyone reading the path sees either the complete old file or the complete new file, and a failed save leaves the previous file untouched. There is no delete-then-rename window either. Serialization matches JsonStringify exactly: deterministic UTF-8, insertion order preserved, LF line ends, no BOM, no final newline. Whatever this writes, LoadJson reads back into an equal document. Returns true on success. On failure it returns 0 and sets a diagnostic: a serialization problem (for example output over the 64 MiB limit) sets JsonError, while a filesystem problem sets FilesystemError with its code and path companions. An indent outside 0 to 8, or a stale handle, is a programming error. Missing folders are not created for you - call CreateDirTree first when the save directory might not exist. The guarantee covers this one file, not a multi-file transaction, and cannot defend against failing hardware or unusual network filesystems. Like every write command in this family it is main-thread-only. For the full rules, see the Application Data language reference. Requires Extended mode. See also: LoadJson, JsonStringify, WriteTextAtomic, CreateDirTree, FilesystemError. |
Example
; SaveJsonAtomic Example ; ---------------------- ; Requires Extended mode. ; Build the save-game document to write to disk save=CreateJsonObject() v=CreateJsonString("Aria") JsonObjectSet save,"player",v FreeJson v v=CreateJsonInteger(1250L) JsonObjectSet save,"gold",v FreeJson v ; SaveJsonAtomic writes a hidden sibling file first, then atomically ; replaces the destination - a crash mid-save can never leave a ; half-written save-game behind. Indent 2 pretty-prints the file. If SaveJsonAtomic(save,"savegame_example.json",2)=0 Then RuntimeError FilesystemError() Print "Saved savegame_example.json ("+FileSize("savegame_example.json")+" bytes)" Print "" ; Load it back to prove the exact document survived the round trip loaded=LoadJson("savegame_example.json") Print "File contents:" Print JsonStringify(loaded,2) Print "" Print "Round trip equal: "+JsonEqual(save,loaded) FreeJson loaded FreeJson save ; Clean up the file this example created DeleteFile "savegame_example.json" Print "" Print "Press any key to close the example" WaitKey End
Index