'How to serialize a Map to JSON string via JSON.stringify in kotlin JS?
My example code is below:
fun main(args: Array<String>) {
val testData = mapOf<String, Any>(
"name" to "albert",
"age" to 26,
"work" to listOf("1", "2", "3")
)
var value = JSON.stringify(testData, { _, value -> value.toString() }, 2)
println(value)
}
The result is "{name=albert, age=26, work=[1, 2, 3]}".
Seems it misses all the double quotes around the property name and string value.
I'm using KotlinJS rather than Kotlin
So, how to solve this?
Solution 1:[1]
This answer comes a few years after the previous accepted answer, but I (who am new to Kotlin) ran into this same problem, and figured out a nice way to achieve this.
- Assume you have a populated Map
- Create an empty js object (seems hacky to me, but this is Kotlin to JS)
- iterate over the your map's "toList" method which provides a Pair
- insert each pair into js object
- grab the js JSON api
and call "stringify" providing your js object. Remember to "toString" at the end
val data: Map<String, Any?> = mapOf() // 1 val export = js("{}") // 2 for (pair: Pair<String, Any?> in data.toList()) { // 3 export[pair.first] = pair.second // 4 } val jsoner = js("JSON") // 5 return jsoner.stringify(export).toString() // 6
Solution 2:[2]
If you wish to simply retrieve a valid JSON string from a Kotlin Map, you can do so using kotlinx.serialization.json:
Json.encodeToString(map)
If you would like to pretty stringify a Kotlin Map, which can be displayed as a pretty JSON in a <pre> tag, you can do:
val jsonString = Json.encodeToString(map) // 1
val jsonObject = JSON.parse<JsonObject>(jsonString) // 2
return JSON.stringify(jsonObject, null, 2) // 3
- Serialize the map to a JSON string using Kotlin serialization
- Parse the JSON string to a Javascript object
- Pretty stringify the Javascript object
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jabgibson |
| Solution 2 | skr |
