Search code examples
javajsonscalatreejson4s

get Json head node value in Scala


I'm a beginner of Scala and using lib "json4s" for JSON parsing, and I have JSON data formatted like below:

scala> val str = """
 | {
 |     "index_key": {
 |         "time":"12938473",
 |         "event_detail": {
 |             "event_name":"click",
 |             "location":"US"
 |         }
 |     }
 | }
 | """

I'm trying to get "index_key" and sign it to a variable. I tried below:

scala> val json = parse(str)
json: org.json4s.JValue = JObject(List((index_key,JObject(List((time,JString(12938473)), (event_detail,JObject(List((event_name,JString(click)), (location,JString(US))))))))))

scala> json.values
res40: json.Values = Map(index_key -> Map(time -> 12938473, event_detail -> Map(event_name -> click, location -> US)))

and I can get the Map from "json.values" by "json.values.head" or "json.values.keys". But I cannot get the first key "index_key" from this map. Could anyone please tell me how to get map key value "index_key"? and what "res40: json.Values" has to do with Map type? Thanks a lot.


Solution

  • head node value can be retrieved like below, thanks to answer from @bjfletcher

    parse(str).asInstanceOf[JObject].values.head._1