0

Morning StackOverflow,

I have a bit of a interesting question today, I was intrigued to know what would be the best way going about converting a decimal separated string into a multi-dimension hash.

For example:

Let say I have the string some.settings.woo = bla

I am looking to get a outcome something like this

{
  "some": {
    "settings": {
      "woo": "bla"
    }
  }
}

But I'm not quite to sure how to go about it effectively

Thanks, Liam

toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131
Liam Haworth
  • 848
  • 1
  • 9
  • 27
  • 3
    Your format looks a lot like HOCON. If so, you could use Typesafe's Config library to transform it into JSON: https://github.com/typesafehub/config – Ryan Dec 28 '14 at 00:53
  • I would also look at typesafe config and see if it works for you before you go for something more complex. – Soumya Simanta Dec 28 '14 at 01:22

3 Answers3

2

One option is to use Rapture's JsonBuffer. Please mind that there's probably a bajillion ways to do this in Scala as JSON libraries are plentiful in the language. This is just a way I happen to know, feel free to explore other libraries.

To quote the docs from the github page I linked to:

An empty JsonBuffer may be created with

val jb = JsonBuffer.empty

and can be mutated with instructions such as

jb.fruit.name = "apple"
jb.fruit.color = "green"
jb.fruit.varieties = List("cox")

resulting in

{
  "fruit": {
    "name": "apple",
    "color": "green",
    "varieties": ["cox"]
  }
}

For more information, refer to the docs concerning mutable JSON representations.

If the input you have is in a string format, you'll have to evaluate it somehow. Here's a Stackoverflow question on how to do this. Be careful though and make sure the input comes from a trusted source.

Community
  • 1
  • 1
toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131
1

Thanks to Ryan and his comment I was reminded of typesafe's config library which made this a really easy walk in the park. It is pretty much a simple two-liner, e.g.

val conf = ConfigFactory.parseString("apache.port=80\nnginx.bind.port=443")
println(conf.root().render(ConfigRenderOptions.concise()))

Returns the following JSON

{
  "apache": { 
    "port":80
  },
  "nginx": {
    "bind": {
      "port": 443
     }
   }
}

This made file stupidly simple, Thanks Ryan!

Library link: https://github.com/typesafehub/config

Liam Haworth
  • 848
  • 1
  • 9
  • 27
0

The best way is to use well tested library, but you can also consider this:

  val parts = "some.settings.woo = bla".split('.')   
  val json = parts.init
    .foldRight("{" + parts.last.replace("=", ":") + "}")("{" + _ + ":" + _ + "}")

  // {some:{settings:{woo : bla}}}
user5102379
  • 1,492
  • 9
  • 9