-2

I have a text file like this demo.txt

name        : Cherry.API.DEV
version2    : Test
uuid        : 0492389a-43243-ewr234342-343d
xx          : {@{fdsfsdfsf}
lastSession : 0.0
activeOK    : True 
learn       : ok

I want to read demo.txt file and then convert as a JSON like this

{"name":"Cherry.API.CI", "variableName":{"module":"Cherry","ID" : "0492389a-43243-ewr234342-343d","systemdebug": "True"}}
bigOteta
  • 1
  • 1
  • share the code you tried so far. – Natsu May 28 '20 at 10:45
  • I used split() function but this is getting confusing – bigOteta May 28 '20 at 10:48
  • 3
    i can give a hint, if you are using split function, split by colon, and trim from both side, you will get the values, put line by line inside the arraylist object or hashmap, and create json. – Natsu May 28 '20 at 10:50

1 Answers1

-1

In Groovy it could be:

import groovy.json.JsonOutput

def str = """name        : Cherry.API.DEV
version2    : Test
uuid        : 0492389a-43243-ewr234342-343d
xx          : {@{fdsfsdfsf}
lastSession : 0.0
activeOK    : True
learn       : ok
"""

def map = [:]
str.splitEachLine(~':', { List<String> list ->
    map.put(list[0].trim(), list[1].trim())
})

def json = JsonOutput.toJson(map)
println json

assert json == '{"name":"Cherry.API.DEV","version2":"Test","uuid":"0492389a-43243-ewr234342-343d","xx":"{@{fdsfsdfsf}","lastSession":"0.0","activeOK":"True","learn":"ok"}'

It prints:

{"name":"Cherry.API.DEV","version2":"Test","uuid":"0492389a-43243-ewr234342-343d","xx":"{@{fdsfsdfsf}","lastSession":"0.0","activeOK":"True","learn":"ok"}

The solution in Java with jackson:

BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/test.txt")));
String line;
Map<String, String> map = new LinkedHashMap<>();
while ((line = reader.readLine()) != null) {
    String[] tokens = line.split(":");
    if (tokens != null && tokens.length > 1) {
        String key = tokens[0];
        String value = tokens[1];
        if (key != null && value != null) {
            map.put(key.trim(), value.trim());
        }
    }
}
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);

Getodac
  • 119
  • 7