Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java Data Science Cookbook

You're reading from   Java Data Science Cookbook Explore the power of MLlib, DL4j, Weka, and more

Arrow left icon
Product type Paperback
Published in Mar 2017
Publisher Packt
ISBN-13 9781787122536
Length 372 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Rushdi Shams Rushdi Shams
Author Profile Icon Rushdi Shams
Rushdi Shams
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Obtaining and Cleaning Data FREE CHAPTER 2. Indexing and Searching Data 3. Analyzing Data Statistically 4. Learning from Data - Part 1 5. Learning from Data - Part 2 6. Retrieving Information from Text Data 7. Handling Big Data 8. Learn Deeply from Data 9. Visualizing Data

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." 
         ] 
} 
You have been reading a chapter from
Java Data Science Cookbook
Published in: Mar 2017
Publisher: Packt
ISBN-13: 9781787122536
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime