jeudi 14 décembre 2017

How to iterate through attributes of a JsonObject recursively?

I'm parsing strings into JSON objects, and I need to be able to recursively iterate through the attributes of the objects. So I'm trying to create a function which iterates through the attributes of the object, and if an attribute is not a primitive then call the function again (recursion) with the attribute itself.

In Javascript I'd solve it like this:

function forEachAttribute(object) {
    for (let key in object) {
        let attribute = object[key];
        if (typeof attribute === "object") {
            forEachAttribute(attribute);
        } else {
            console.log(key + ": " + attribute);
        }
    }
}

let myObject = {
    innerObject: {
        x: 123
    },
    y: 456
};

forEachAttribute(myObject);

But I'm moving away from Javascript, and trying to learn how to use Kotlin instead. So I found a way to iterate through the attributes of a JSON object.

But I don't quite understand how to determine if the attribute is a primitive or not.

import kotlin.js.Json

fun iterateThroughAttributes(jsonObject: Json) {
    for (key in js("Object").keys(jsonObject)) {
        val attribute = jsonObject[key]
        // How do I determine if the attribute is a primitive, or not?
    }
}

fun main (args: Array<String>) {
    val someString = "(some json string)"
    val jsonObject = JSON.parse<Json>(someString)
    iterateThroughAttributes(jsonObject)
}

Can someone help?





Aucun commentaire:

Enregistrer un commentaire