JSONUtils

This is a helper class to facilitate usage of JSON files.

Methods

Type

Name

Dictionary / Array

load_json_file

Dictionary / Array

load_json_buffer

void

save_json_file

void

make_system_specific

Dictionary

map_array_by_key

String

format_string_with_substitutes


Dictionary / Array load_json_file (filepath: String)

Loads a JSON file and returns it as a Dictionary or as an Array. If the file does not exist or is invalid, an empty dictionary is returned.


Dictionary / Array load_json_buffer (data: String)

Loads a JSON file from data in memory, and returns it as a Dictionary or as an Array. If the data is invalid, an empty dictionary is returned.


void save_json_file (json: Dictionary, file_path: String)

Saves a dictionary as a JSON file to file_path.


void make_system_specific (json: Dictionary, curr_system: String)

Edits a dictionary in-place to remove variable Paths, taking into account the current system. Used internally to load configurations dependent on the current system.

var data = {
        "foo": "bar",
        "path": {
                "windows": [
                        "C:\\foo\\bar",
                        "C:\\foo\\bar2"
                ],
                "macos": "/Applications/foo/bar",
                "linux": "/bin/foo/bar"
        }
}

JSONUtils.make_system_specific(data, "windows")
# Returns {"foo": "bar", "path": ["C:\\foo\\bar", "C:\\foo\\bar2"]}

Dictionary map_array_by_key (input: Array, key: String)

Given an array of dictionaries with a given key, returns a dictionary mapped by the key’s value.

var data = [
        {"id": "foo", "name": "Foo"},
        {"id": "bar", "name": "Bar"}
]

JSONUtils.map_array_by_key(data, "id")
# Returns {"foo": {"id": "foo", "name": "Foo"}, "bar": {"id": "bar", "name": "Bar"}}

String format_string_with_substitutes (raw_str: String, substitutes: Dictionary, tk_start: String = "{", tk_end: String = "}", remove_empty: bool = false)

Takes a string with embedded tokens and replaces them with values from a dictionary. Tokens are defined by tk_start and tk_end, and are {} by default. If remove_empty is true, tokens that are not found in the dictionary are removed from the string.

var raw_str = "Hello {name}! You are {age} years old."

JSONUtils.format_string_with_substitutes(raw_str, {"name": "John", "age": 30})
# Returns "Hello John! You are 30 years old."

JSONUtils.format_string_with_substitutes(raw_str, {"name": "John"})
# Returns "Hello John! You are {age} years old."

JSONUtils.format_string_with_substitutes(raw_str, {"name": "John"}, "{", "}", remove_empty = true)
# Returns "Hello John! You are years old."