Page 1 of 1

Import Json Data Easier

Posted: Thu Sep 22, 2022 10:38 pm
by Counter Arts
Have a ton of data you want to import? Do you hate defining a billion gets/sets for each custom data class definition? Hate writing python just to build the definitions?

This code is for you!

But how do you use it? Simple!

This is the code to load the json file.

Code: Select all

init 100 python:

    import json

    baseData = json.load(renpy.file("plotSetA.json"))

    for i in baseData["locations"]:

        Location.loadFromJsonObject(i)
This is the json file

Code: Select all

{"locations" : [
		{
			"id" : 1,
			"name" : "Cafe",
			"techName" : "cafe",
			"imageName" : "cafe",
			"xpos" : 20,
			"ypos" : 20,
			"filePrefix" : "bgs/",
			"variantFlags" : []

		},
		{
			"id" : 2,
			"name" : "Hospital",
			"techName" : "hospital",
			"imageName" : "hospital",
			"xpos" : 80,
			"ypos" : 20,
			"filePrefix" : "bgs/",
			"variantFlags" : ["moon"]

		},
		{
			"id" : 3,
			"name" : "Park",
			"techName" : "pafe",
			"imageName" : "pafe",
			"xpos" : 20,
			"ypos" : 20,
			"filePrefix" : "bgs/",
			"variantFlags" : []

		},
		{
			"id" : 4,
			"name" : "Shrine",
			"techName" : "shrine",
			"imageName" : "shrine",
			"xpos" : 50,
			"ypos" : 50,
			"filePrefix" : "bgs/",
			"variantFlags" : []

		},

		{
			"id" : 5,
			"name" : "Waterside Shops",
			"techName" : "waterside",
			"imageName" : "waterside",
			"xpos" : 80,
			"ypos" : 80,
			"filePrefix" : "bgs/",
			"variantFlags" : []

		}
	]
}
This is how location definition class looks like. Notice how every location being created is being indexed by id in "LocationDefs"!

Code: Select all

init 1 python:

    LocationDefs = {}

    @Loadable
    class Location:


        def __init__(self, id):

            self.id = id
            self.name = ""
            self.techName = ""
            self.imageName = ""
            self.xpos = 0
            self.ypos = 0
            self.variantFlags = []
            self.filePrefix = ""

            LocationDefs[id] = self
            
And here is the code to import into your Ren'Py project!

Code: Select all

init -2 python:

    import inspect
    import json

    # Class decorator
    # requires an init function that only takes an ID
    def Loadable(cls):

        temp = cls(-1)
        fieldsToGrab = filter(lambda i: not i.startswith("_") and not i.isupper() , dir(temp))


        @staticmethod
        def innerJsonLoadable(jsonData):

            current = cls(jsonData["id"])

            for i in fieldsToGrab:
                if i in jsonData:

                    setattr(current, i, jsonData[i] )

            return current


        cls.loadFromJsonObject = innerJsonLoadable

        return cls