Iterating over Json properties

Hi there!

I’m unsuccessfully trying to find a way to iterate over a Json object (which is expected to only contain properties with String values) so that I can fill a Map<String,String> from it. In either way I end up with an illegal cast exception.

Does anyone know how to do this?

Jørund

Could you please show the code that you’re using?

Thanks for following up!

This is what we have tried:

private fun jsonToMap(json: Json): Map<String, String> {
    val map: MutableMap<String, String> = linkedMapOf()
    for (key in json) {
        map.put(key, json[key] as String)
    }

    // or 
    for( (name, value) in json ) {
        map.put(name, value as String)
    }
    return map
}

Hi, @jvskriubakken, try this:

private fun jsonToMap(json: Json): Map<String, String> {
    val map: MutableMap<String, String> = linkedMapOf()
    for (key in js("Object").keys(json)) {
        map.put(key, json[key] as String)
    }
    return map
}
2 Likes

Thanks! It worked!

My 2cents for future references:

val jsObject = js("Object")

private fun parse(json: dynamic): Map<String, Transaction> {
    val entries= jsObject.entries(json) as Array<Array<dynamic>>
    
    return entries
            .map { entry ->
                entry[0] as String to parseObject(entry[1])
            }.toMap()
}

where in your case the parseObject method would be

private fun parseObject(json:dynamic) = json as String