Json is not defined in Kotlin 1.0.2

Hello people!
I’m trying to upgrade to latest 1.0.2 and is experiencing that Json is no longer defined. Is this correct and if so what is the remedy? Could not find anything about in the changelog.

Guidance appreciated!

Thanks!

Jørund

Forgot to mention that I’m compiling to Javascript using Maven - and that this was experienced as an Javascript error in the browser.

So, I’m trying to upgrade to version 1.0.2 again.

I have the following line of code:
val json = Json()

Which will compile to Javascript like this:
var json = new Json();

However if fails runtime, saying that ‘Json’ is undefined.

Is there any changes in Kotlin 1.0.2 that makes this reasonable?

If I take a look in the Kotlin source code I see that Json is defined in package kotlin.js in the js.libraries module:
@native public class Json()

Has anyone else tried using Json with version 1.0.2?

Hi, @jvskriubakken!

Are you sure that it worked before? We didn’t change anything here since 1.0.0.

It’s the bug that Json declared as class (I’ve created the issue).

To create simple object you can use json function, like :

val a = json() // a = {}
val b = json("foo" to 1, "bar" to baz) // b = {"foo" : 1, "bar", "baz"}

Hi Zalim and thanks for following up!

Sorry, I’ve gave you incorrect descriptions of my problem. I’m of course not creating new json objects using Json but using json().

My problem occurs when casting to a Json object when reading json:

val json = json()
val someObject = json()
json.set("someObject", someObject)

json.get("someObject") as Json? // This fails with: Json is not defined

This generates:

          var tmp$0;
          var json = Kotlin.modules['stdlib'].kotlin.js.json_eoa9s7$([]);
          var someObject = Kotlin.modules['stdlib'].kotlin.js.json_eoa9s7$([]);
          json['someObject'] = someObject;
          (tmp$0 = json['someObject']) == null || Kotlin.isType(tmp$0, Json) ? tmp$0 : Kotlin.throwCCE();

Another might be related problem.

When I’m trying to log the json to the console I also get and error about “slice” not being defined:
val json = json()
json.set(“a”, 1)
console.log(json)

Generates:
var tmp$0;
var json = Kotlin.modules[‘stdlib’].kotlin.js.json_eoa9s7$();
json[‘a’] = 1;
console.log(json.slice());

Both this and previous example was tested in function: fun main(vararg args: String)

I’m currently using version 1.0.1-2, where both casting to Json and logging the json to the console works.

The bug with slice already fixed and will be available in 1.0.3.
Temporary You can use println instead of console.log.

The problem with the cast is the known issue, fell free to vote to get notifications about updates.
As the workaround you can use helper function:

inline fun <T> Any?.unsafeCast(): T = asDynamic()
...
json.get("someObject").unsafeCast<Json?>()
1 Like

Thanks a lot for the help! I will look at implementing the workaround as soon as I get my hands free.