Json in GDScript

GDScript provides built-in support for JSON encoding and decoding, including to and from built-in and custom data types.

extends Node

# We'll use these two classes to demonstrate encoding and
# decoding of custom types below.
class Response1:
    var page: int
    var fruits: Array

    func _init(p: int, f: Array):
        page = p
        fruits = f

class Response2:
    var page: int
    var fruits: Array

    func _init(p: int, f: Array):
        page = p
        fruits = f

func _ready():
    # First we'll look at encoding basic data types to
    # JSON strings. Here are some examples for atomic values.
    print(JSON.print(true))
    print(JSON.print(1))
    print(JSON.print(2.34))
    print(JSON.print("gopher"))

    # And here are some for arrays and dictionaries, which encode
    # to JSON arrays and objects as you'd expect.
    var slc_d = ["apple", "peach", "pear"]
    print(JSON.print(slc_d))

    var map_d = {"apple": 5, "lettuce": 7}
    print(JSON.print(map_d))

    # The JSON module can automatically encode your
    # custom data types. It will include all properties
    # in the encoded output.
    var res1_d = Response1.new(1, ["apple", "peach", "pear"])
    print(JSON.print(res1_d))

    var res2_d = Response2.new(1, ["apple", "peach", "pear"])
    print(JSON.print(res2_d))

    # Now let's look at decoding JSON data into GDScript
    # values. Here's an example for a generic data structure.
    var json_str = '{"num":6.13,"strs":["a","b"]}'

    # We need to provide a variable where the JSON
    # module can put the decoded data. This Dictionary
    # will hold a dictionary of strings to arbitrary data types.
    var dat = JSON.parse(json_str)
    if dat.error == OK:
        dat = dat.result
        print(dat)

    # In order to use the values in the decoded dictionary,
    # we'll need to convert them to their appropriate type.
    # For example here we convert the value in `num` to
    # the expected float type.
    var num = dat["num"] as float
    print(num)

    # Accessing nested data requires a series of conversions.
    var strs = dat["strs"] as Array
    var str1 = strs[0] as String
    print(str1)

    # We can also decode JSON into custom data types.
    # This has the advantages of adding additional
    # type-safety to our programs.
    json_str = '{"page": 1, "fruits": ["apple", "peach"]}'
    var res = JSON.parse(json_str)
    if res.error == OK:
        res = res.result
        var response = Response2.new(res["page"], res["fruits"])
        print(response.page)
        print(response.fruits[0])

    # In GDScript, we can directly print dictionaries and arrays,
    # which will output them in a JSON-like format.
    var d = {"apple": 5, "lettuce": 7}
    print(d)

To run this script, save it as a .gd file and attach it to a Node in your Godot scene. When you run the scene, you’ll see the output in the Godot output panel.

Note that GDScript doesn’t have a direct equivalent to Go’s json.Marshal and json.Unmarshal. Instead, it uses JSON.print() for encoding and JSON.parse() for decoding. Also, GDScript uses Dictionary instead of Go’s map, and Array instead of Go’s slices.

The concepts of streaming JSON directly to writers is not directly applicable in GDScript, as it’s primarily used within the Godot game engine context.

Remember to handle potential errors when parsing JSON, as shown in the example with the error property of the parse result.