jawn
jawn copied to clipboard
How does one convert JSON object with list into something iterable?
I know I can access each indexing e.g. .get(0) but how do I iterate over it?
val list = jawn.ast.JParser.parseFromString("""{"stuff": [1,2,3]}""").get
val stuff = list.get("stuff")
for (item <- stuff) println(item)
Hi @martez81 -- sorry I missed this!
I am planning on adding support for this in a new version, but currently you can just do something like this:
val stuff = list.get("stuff")
for { item <- stuff.vs } println(item)
The vs member is an Array[JValue] and should allow you to use Scala collection methods.
Ahh this is all I really need thanks!
Sorry, just tried this and list.get("stuff") returns JValue and there is no vs member :(
Here's exactly how I use it
val parsed = jawn.ast.JParser.parseFromPath(s"${Config.home}/$name/_table.json").get
val parsedCols = parsed.get("columns") // want to iterate over this
and json contents
{
"name": "correla_dataset_small",
"columns": [{
"name": "age",
"type": "TinyIntType",
"encoder": "Dense"
}, {
"name": "fname",
"type": "VarCharType",
"size": 15,
"encoder": "Dict"
}, {
"name": "lname",
"type": "VarCharType",
"size": 30,
"encoder": "Dict"
}]
}
using version 0.8.3
@non is adding a getIterable and asIterable to JValue and implementing it in JArray the right approach? What about adding getMap and asMap to JValue and implementing it in JObject
I have a PR out, please have a look: https://github.com/non/jawn/pull/68
I had a similar problem.
I got hold of the problem by finding out that the object I got was already a JArray. However, I used it like a JValue. JValue doesn't have a vs as @martez81 mentioned above. JArray on the other hand does have an attribute vs.
I managed to use the JSON array by converting it to such:
import jawn.ast.JParser
import jawn.ast.JArray
val list = JParser.parseFromString("""{"stuff": [1,2,3]}""").get
val stuff = list.get("stuff").asInstanceof[JArray]
for (item <- stuff) println(item)