How to read a JSON file (SOLVED)

Hi, sorry for the noob question :sweat_smile: How can I read a JSON file and show the data on screen? Thank you in advance.

It is super easy! But don’t worry noob questions are always welcome and it’s always encouraged to ask them, be sure to search first before asking too. A tip is to go to google and use site:defold.com with your search term to find what you are looking for.

An important thing to know is Defold only includes files it references. Normally it wouldn’t know to include files like JSON files in its bundle so you have to tell it to force include the folders these files are in via the custom resources field in the game.project file.

[project]
title = ReadJSONFile
custom_resources = res/

This will include all of the stuff in a res folder so be sure everything you would want in such a folder should be shipped with your game.

Now for reading the file

function init(self)
	local test_json_file = sys.load_resource("/res/json/test.json")
	local test_json_table = json.decode(test_json_file)
	pprint(test_json_table)
end

This loads the JSON resource, decodes it, then prints all of its data to the console.

Here’s an example project with this setup.

ReadJSONFile.zip (2.8 KB)

Serializing tables to JSON and then saving them as files is another topic but it’s possible to do too.

22 Likes

sorry for the very very late reply :sweat_smile: thank you very much

1 Like

Just what I was looking for, thanks!

1 Like

It was really helpful, thank you

1 Like