Book Image

Java Data Science Cookbook

By : Rushdi Shams
Book Image

Java Data Science Cookbook

By: Rushdi Shams

Overview of this book

If you are looking to build data science models that are good for production, Java has come to the rescue. With the aid of strong libraries such as MLlib, Weka, DL4j, and more, you can efficiently perform all the data science tasks you need to. This unique book provides modern recipes to solve your common and not-so-common data science-related problems. We start with recipes to help you obtain, clean, index, and search data. Then you will learn a variety of techniques to analyze, learn from, and retrieve information from data. You will also understand how to handle big data, learn deeply from data, and visualize data. Finally, you will work through unique recipes that solve your problems while taking data science to production, writing distributed data science applications, and much more - things that will come in handy at work.
Table of Contents (16 chapters)
Java Data Science Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Writing JSON files using JSON.simple


Just like XML, JSON is also a human-readable Data Interchange Format that is lightweight. It stands for JavaScript Object Notation. This is becoming a popular format generated and parsed by modern web applications. In this recipe, you will see how you can write JSON files.

Getting ready

In order to perform this recipe, we will require the following:

  1. Download json-simple-1.1.1.jar from https://code.google.com/archive/p/json-simple/downloads and include the JAR file as external library to your Eclipse project.

How to do it...

  1. Create a method named writeJson(String outFileName) that takes the name of the JSON file we will be generating as output with the JSON information in this recipe.

  2. Create a JSON object and use the object's put() method to populate a few fields. For instance, say your fields will be books and their authors. The following code will be creating a JSON object and populate a book name from the Harry Potter series and its author's name:

            JSONObject obj = new JSONObject(); 
              obj.put("book", "Harry Potter and the Philosopher's Stone"); 
              obj.put("author", "J. K. Rowling");
    
  3. Next, say that we have three reviewer comments for this book. They can be put together in a JSON array. The array can be populated as follows. First, we use add() of the array object to add the reviews. When all the reviews are added to the array, we will be putting the array to the JSON object we created in the previous step:

    JSONArray list = new JSONArray(); 
     
    list.add("There are characters in this book that will remind us of all the people we have met. Everybody knows or knew a spoilt, overweight boy like Dudley or a bossy and interfering (yet kind-hearted) girl like Hermione"); 
     
    list.add("Hogwarts is a truly magical place, not only in the most obvious way but also in all the detail that the author has gone to describe it so vibrantly."); 
     
    list.add("Parents need to know that this thrill-a-minute story, the first in the Harry Potter series, respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles. "); 
     
    obj.put("messages", list); 
    
  4. We will be writing down the information in the JSON object to an output file because this file will be used to demonstrate how we can read/parse a JSON file. The following try...catch code blocks write down the information to a JSON file:

            try { 
     
                     FileWriter file = new FileWriter("c:test.json"); 
                     file.write(obj.toJSONString()); 
                     file.flush(); 
                     file.close(); 
     
            } catch (IOException e) { 
                     //your message for exception goes here. 
            } 
    
  5. The content of the JSON object can also be displayed on the standard output as follows:

            System.out.print(obj); 
    
  6. Finally, close the method:

        } 

The entire class, the method described in this recipe, and the driver method to call the method with an output JSON file name are as follows:

import java.io.FileWriter; 
import java.io.IOException; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
 
public class JsonWriting { 
 
   public static void main(String[] args) { 
      JsonWriting jsonWriting = new JsonWriting(); 
      jsonWriting.writeJson("C:/testJSON.json"); 
   } 
 
   public void writeJson(String outFileName){ 
      JSONObject obj = new JSONObject(); 
      obj.put("book", "Harry Potter and the Philosopher's Stone"); 
      obj.put("author", "J. K. Rowling"); 
 
      JSONArray list = new JSONArray(); 
      list.add("There are characters in this book that will remind us  
        of all the people we have met. Everybody knows or knew a 
          spoilt, overweight boy like Dudley or a bossy and interfering   
            (yet kind-hearted) girl like Hermione"); 
      list.add("Hogwarts is a truly magical place, not only in the most 
        obvious way but also in all the detail that the author has gone     
          to describe it so vibrantly."); 
      list.add("Parents need to know that this thrill-a-minute story, 
        the first in the Harry Potter series, respects kids'  
          intelligence and motivates them to tackle its greater length 
            and complexity, play imaginative games, and try to solve 
              its logic puzzles. "); 
 
      obj.put("messages", list); 
 
      try { 
 
         FileWriter file = new FileWriter(outFileName); 
         file.write(obj.toJSONString()); 
         file.flush(); 
         file.close(); 
 
      } catch (IOException e) { 
         e.printStackTrace(); 
      } 
 
      System.out.print(obj); 
   } 
}

The output file will be containing data as follows. Note that the output shown here has been modified to increase readability, and the actual output is one, big, flat piece of text:

{ 
"author":"J. K. Rowling", 
"book":"Harry Potter and the Philosopher's Stone", 
"messages":[ 
         "There are characters in this book that will remind us of all the people we have met. Everybody knows or knew a spoilt, overweight boy like Dudley or a bossy and interfering (yet kind-hearted) girl like Hermione", 
         "Hogwarts is a truly magical place, not only in the most obvious way but also in all the detail that the author has gone to describe it so vibrantly.", 
         "Parents need to know that this thrill-a-minute story, the first in the Harry Potter series, respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles." 
         ] 
}