user1 user1 - 21 days ago 6
JSON Question

How can i write in a file JSON Format result?

I'm new to this point , I have file contains 50.000 tweets with JSON format , i need to convert or make it readable . I tried to use this code but How can i make it write in a file ?

package analysis;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Scanner;
import com.google.gson.Gson;

public class p {
public static void performAnalysis() {
File tweets;

String[] categories;
tweets = new File("/home/user/Desktop/tweets.txt");
categories = tweets.list();

for (int i = 0; i < categories.length; ++i) {
String category = categories[i];
File file = new File(tweets, category);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String rawTweet = sc.nextLine().trim();
if (rawTweet.equals(""))
continue;
Tweet parsedTweet = new Gson().fromJson(rawTweet, Tweet.class);
//System.out.println(parsedTweet.getBody());

}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}


the other class is

package analysis;
import java.io.Serializable;
public class Tweet implements Serializable{
private long ID;
private String body;

public Tweet(long tweetID, String body)
{
this.body = body;
ID = tweetID;
}

public Tweet(long tweetId)
{
ID = tweetId;
}
public String getBody()
{
return body;
}

public void setBody(String body){
this.body = body;
}
public long getID()
{
return ID;
}

public void setId(long tweetId)
{
ID = tweetId;
}
}


the file which contains
tweets like

{"filter_level":"low","retweeted":false,"in_reply_to_screen_name":null,"possibly_sensitive":false,"truncated":false,"lang":"en","in_reply_to_status_id_str":null,"id":712044789663924224,"extended_entities":{"media":[{"sizes":{"thumb":{"w":150,"resize":"crop","h":150},"small":{"w":340,"resize":"fit","h":227},"medium":{"w":600,"resize":"fit","h":400},"large":{"w":1024,"resize":"fit","h":683}},"source_user_id":38142624,"media_url":"http://pbs.twimg.com/media/Cdv_qOUW4AAfExX.jpg","display_url":"pic.twitter.com/OFpmAARFZR","type":"photo","url":"https://t.co

Answer

If this question is really about formatting an querying a JSON file, I'd skip the programming part and just use any JSON browsing tool out there. E.g. try opening that file in Firefox Developer Edition.

Another option is to use jq, and redirect the output to a file (assuming you use some UNIX/UNIX-like shell):

cat tweets.json | jq . > output.json 

That would be a large file, though. You can use ja's querying syntax to make a few smaller files.