3

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"
}
}
ycomp
  • 8,316
  • 19
  • 57
  • 95
  • You have a method definition there. But where is that coming from? Some library? It is really not clear what you are asking for. – GhostCat Jun 29 '17 at 06:59
  • @GhostCat stdlib : [parse - Kotlin Programming Language](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/-j-s-o-n/parse.html) – ycomp Jun 29 '17 at 07:01
  • Interesting. But I am not too much into kotlin ;-( – GhostCat Jun 29 '17 at 07:08
  • @GhostCat kotlin JS is good but a bit buggy still, but overall I'm pleased – ycomp Jun 29 '17 at 07:16

1 Answers1

4

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.

Ralf Stuckert
  • 2,120
  • 14
  • 17