Search code examples
kotlinkotlin-interopkotlin-js-interop

Parsing JSON with Kotlin JS 'fun <T> parse(text: String): T`?


How can I use

fun <T> parse(text: String): T

to parse JSON in Kotlin JS?

e.g. how can I parse this JSON string?

{
"couchdb": "Welcome",
"version": "2.0.0",
"vendor": {
    "name": "The Apache Software Foundation"
}
}

Solution

  • It depends what you want to do with the parsed JSON. The easiest way would be

    val jsonAny = JSON.parse<Any>(text);
    

    Or you could parse it as a Json, which would allow you to access the properties:

    val json = JSON.parse<Json>(text);
    println(json["version"]);
    

    Or - if you want to use the strict typing of kotlin - you may want to define a class that represents the structure and use its properties:

    data class CouchDB(val version:String)
    
    val jsonCouchDb = JSON.parse<CouchDB>(text);
    println(jsonCouchDb.version)
    

    After all, it will always be the same JS object returned by the javascript JSON.parse() method, Kotlin just introduces types here.