How do I load a JSON file?



I’m learning how to work with Kotlin and Javascript, and right now, I’m trying to load a .json file that’s present on the same server the website itself is hosted from.

How would I go about this? There’s a JSON object but the documentation doesn’t really say how to use it.



Actually, (according to documentation) it’s just declaration to use JS builtin JSON object, you can find more info about it on MDN, for example.


Right, so I can use it to parse a string into a JSON object graph, the problem I’m having is that I don’t undertstand where to get this string from, ie. how do I read the file?


You can use Fetch API or XMLHttpRequest API for that.


I can’t really get the fetch API to work, neither with resources on the same site nor with a site like pastebin. For example:

Request("").text().then(onFulfilled = {println(it)})

Shouldn’t that work?


This code works for me:

import kotlin.browser.*
import org.w3c.fetch.*

fun main(args: Array<String>) {
    window.fetch(Request("")).then(onFulfilled = {
        it.text().then(onFulfilled = {


And how would this work for a file on the same site? Trying to fetch "res/test.txt" results in the following error:
Main.kt:5 Fetch API cannot load file:///D:/Programming/Kotlin/SiteTest/web/res/test.txt. URL scheme must be "http" or "https" for CORS request.


Thats a browser safety feature. Imagine any site can read any file on your device thats bad for security.
You have to serve files with some kind of server.
For tutorial porpoises there are simplistic web servers built in node.js/python/ IDEA itself and many others.
If you are using IDEA try opening html file with IDE it will spin up internal server and serve whole folder contents. You can access files in there with relative paths in html.


This won’t work with filesystem, it’s not Kotlin constraint it’s rather because of XSS protection in browsers. You should serve your HTML, JS and files from HTTP server.


Ah but using relative paths like that will start working when I host them on an actual server?

I didn’t even think about the security implications this would have if it actually worked :slight_smile: . The build-in IDEA web server will do fine for now, thanks for the suggestion @Konstantin-Khvan.


Yes, this should work. res/test.txt will load file relative to a HTML page you are sending request from. /res/test.txt will load file from the current host and corresponding path (for example, http://localhost:8080/res/test.txt).


There are also quick and dirty one-liners to do basic web serving out of a file folder:


I know it’s not strictly Kotlin-related any more, but is there a way to start the build-in Idea server as a run configuration? Otherwise I’ll have to resort to one of the web serving one-liners :slight_smile:.