LoadJson ( file$ )
Parameters
| file$ - path of the JSON file to load |
Description
|
Loads and parses a strict UTF-8 JSON file, returning a new owned JSON handle or 0. LoadJson is the read half of a save system: it opens the file, reads its bytes and parses them exactly like ParseJson, all in one call. The natural partner is SaveJsonAtomic - what one writes, the other reads back byte-for-byte. The returned handle is owned by you: release it with FreeJson when you are done. A return value of 0 means the load failed, and there are two distinct ways that can happen: 1. The file could not be read (missing, locked, unreadable path) - FilesystemError describes the problem and the JSON diagnostic is cleared. 2. The file was read but its content is not valid JSON - JsonError and its companions describe the problem instead. Checking both diagnostics tells you whether to blame the disk or the data. In Extended mode the path is strict UTF-8, so save folders named by players in any language work; invalid UTF-8 in a path is rejected. The same strict parsing rules and limits as ParseJson apply (64 MiB of source, 128 levels of nesting, no duplicate keys, comments or trailing commas). LoadJson is read-only and worker-safe, so a Job can index save files in the background - but JSON handles never cross a Job boundary, so each worker loads and frees its own documents. For the full rules, see the Application Data language reference. Requires Extended mode. See also: SaveJsonAtomic, ParseJson, FreeJson, JsonError, FilesystemError. |
Example
; LoadJson Example ; ---------------- ; Requires Extended mode. q$=Chr(34) ; Double-quote character, for building JSON text ; First create a settings file for this example to load settings_text$="{"+q+"music_volume"+q+":80,"+q+"fullscreen"+q+":false}" WriteTextAtomic "settings_example.json",settings_text Print "Wrote settings_example.json: "+settings_text Print "" ; LoadJson reads and parses a strict UTF-8 JSON file in one step, ; returning an owned handle (0 = file or parse failure) settings=LoadJson("settings_example.json") If settings=0 Then RuntimeError JsonError() Print "Loaded OK, handle="+settings Print "" ; Read the loaded settings back out volume=JsonObjectGet(settings,"music_volume") Print "music_volume = "+JsonInteger(volume) FreeJson volume fullscreen=JsonObjectGet(settings,"fullscreen") Print "fullscreen = "+JsonBoolean(fullscreen) FreeJson fullscreen FreeJson settings ; Clean up the file this example created DeleteFile "settings_example.json" Print "" Print "Press any key to close the example" WaitKey End
Index