0

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.

keypoint
  • 2,268
  • 4
  • 31
  • 59

2 Answers2

2

I'm not familiar with json4s specifically but I'm pretty sure it acts like most other json libraries in that it provides you with a nice DSL for extracting out data from parsed json.

I had a look at the docs and found this:

scala> val json =
  ("person" ->
    ("name" -> "Joe") ~
    ("age" -> 35) ~
    ("spouse" ->
      ("person" ->
        ("name" -> "Marilyn") ~
        ("age" -> 33)
      )
    )
  )

scala> json \\ "spouse"
res0: org.json4s.JsonAST.JValue = JObject(List(
      (person,JObject(List((name,JString(Marilyn)), (age,JInt(33)))))))

The \\ operator traverses the JSON structure and extracts the data at that node. Note that the double slash operator in this case works recursively, to reach the root node you would use a single slash, i.e '\'.

For your example it would be json \ "index_key" which would return the JSON at that node.

goralph
  • 1,076
  • 9
  • 18
  • hi @michael-kendra, thank you very much for your detailed answer. what if, use your json sample, I want to get the first node key value, not the json content of the first node? something like "val firstNode = 'person' ". – keypoint Jul 06 '15 at 06:14
-1

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

parse(str).asInstanceOf[JObject].values.head._1 
keypoint
  • 2,268
  • 4
  • 31
  • 59