2

I'm new to groovy and this might be very trivial. I have a string that has the exact format as groovy's map (there are also map within map).

All I want to do is just convert the string format to groovy map. I tried the this but my string is too big for Eval.me to compute. Is there any other way to do this?

My string has format somewhat like this:-

[
    'item1':[
        [
            'subitem11':1, 
            'subitem21':'name', 
            'subitem31':'nametwo'
        ],
        [
            'subitem21':'1', 
            'subitem22':'name2'
        ],
        [
            'subitem31':'2', 
            'subitem32':'name3'
        ]
    ],
    'item2':'itemContent', 
    'item3':'itemContent3', 
    'item4':'itemContent4', 
    'item5':'itemContent5', 
    'item6':'itemContent6', 
    'item7':'itemContent7', 
    'item7':['subitem71', 'subitem72']
]
Community
  • 1
  • 1
shriek
  • 5,605
  • 8
  • 46
  • 75

1 Answers1

5

It's may be not an easy or clear solution but it can work.

First about "too big for computing string", Guilame give a nice answer in similar question link.(First answer). He pointed, that Script evaluation isn't suited for large data processing, and you will hit JVM limitations very soon, ever through you use some hacks or optimisations.

You can try to split data, but it's not very good solution too.

Your Groovy-like format can be interpreted as YAML.

So, you can use YAML parser libraries, to extract data from that string.

ie:

@Grab( 'org.yaml:snakeyaml:1.13' ) 
import org.yaml.snakeyaml.Yaml

def data = new Yaml().load( string )

Also, there are several YAML-JSON converters. If you can prepare your data in such a way, Groovy new JSON parser is a very fast.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Seagull
  • 13,484
  • 2
  • 33
  • 45
  • Sweet. I knew there had to be some other way. Thanks. – shriek Feb 12 '14 at 20:11
  • How to make the opposite : Groovy Map --> to String in YAML format ? – Abdennour TOUMI Sep 03 '20 at 09:57
  • 1
    Hey, @AbdennourTOUMI ! Normally, if you want to ask something on StackOverflow, best way is to create a separate question. Answering your Q, that's super simple. You can use any YAML serialiser. For example Jackson's YAML module https://github.com/FasterXML/jackson-dataformats-text/tree/master/yaml Anything Java that can convert an object to YAML will work for Groovy too. – Seagull Sep 03 '20 at 13:56
  • @Seagull Done! https://stackoverflow.com/questions/63726800/convert-groovy-map-to-string-in-yaml-format – Abdennour TOUMI Sep 03 '20 at 15:24