Home » Java » json – Scraping Data from the List java-Exceptionshub

json – Scraping Data from the List java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a list which looks like below:

[
  StartingNmap7.60(https: //nmap.org)at2020-02-1713: 32IST,
  Nmapscanreportfor192.168.1.1(192.168.1.1),
  Hostisup(0.0012slatency).,
  Nmapscanreportforbevywise_37e0(192.168.1.4),
  Hostisup(0.14slatency).,
  Nmapscanreportforshiv-thinkpad-t420(192.168.1.5),
  Hostisup(0.0072slatency).,
  Nmapscanreportforvivo-1726(192.168.1.12),
  Hostisup(0.028slatency).,
  Nmapscanreportforrealme-5(192.168.1.13),
  Hostisup(0.13slatency).,
  Nmapdone: 256IPaddresses(5hostsup)scannedin21.02seconds
]

It looks like messy. I want to get some data from that list.I want the required output to be like below:

[{"host name":"192.168.1.1","IP address":192.168.1.1"},
{"host name":"bevywise_37e0","IP address:"192.168.1.4"},
{"host name":"shiv-thinkpad-t420","IP address":"192.168.1.5"},
{"host name":"vivo-1726","IP address":"192.168.1.12"},
{"host name":"realme-5","IP address":"192.168.1.13"}]

Since I am new to java, I can’t figure out how to make it. Help me with some solutions.

How to&Answers:

If this list is list/array of strings you can do the folowing

  1. Filter your list by string prefix, in your case it will be

    String prefix = "Nmapscanreportfor";
    
  2. Create formating template where you will put parsed data

    String template = “{\”host name\”:\”%s\”,\”IP address\”:%s\”}”;

  3. Then iterate over your list and parse host name and ip address. String.indexOf() will be usefull. E.g. to get hostname, you can do

    listEntry.substring(prefix.length(), entry.indexOf("("))
    

    For ip it wil be similar, just find first “(” and last “)”. String between is your ip address.

  4. And when you will have hostname and ip address you can use String.format() method to fill template string placeholders.

To iterate over the list you can use for loop or streams. With streams it will look pretty nice

        List<String> newList = Arrays.stream(array) //if it's array of list.stream() if it's list
            .filter(entry -> entry.startsWith(prefix))
            .map(entry -> String.format(template, %your hostname%, %your ip address%))
            .collect(Collectors.toList());