Get fresh updates from Hortonworks by email

Once a month, receive latest insights, trends, analytics information and knowledge of Big Data.


Sign up for the Developers Newsletter

Once a month, receive latest insights, trends, analytics information and knowledge of Big Data.


Get Started


Ready to Get Started?

Download sandbox

How can we help you?

* I understand I can unsubscribe at any time. I also acknowledge the additional information found in Hortonworks Privacy Policy.
closeClose button
September 27, 2012
prev slideNext slide

JSONize Anything in Pig with ToJson

The need for a ToJson EvalFunc

When integrating Pig with different NoSQL ‘databases,’ or when publishing data from Hadoop, it can be convenient to JSONize your data. Although Pig has JsonStorage, there hasn’t been a ToJson EvalFunc. This has been inconvenient, as in our post about Pig and ElasticSearch, such that for creating JSON for ElasticSearch to index, tricks like this were necessary:

store enron_emails into '/tmp/enron_emails_elastic' using JsonStorage();
json_emails = load '/tmp/enron_emails_elastic' AS (json_record:chararray);
/* Now we can store our email json data to elasticsearch for indexing with message_id. */
store json_emails into 'es://enron/email?json=true&size=1000' USING
  com.infochimps.elasticsearch.pig.ElasticSearchStorage('/me/elasticsearch-0.18.6/config/elasticsearch.yml', '/me/elasticsearch-0.18.6/plugins')

Note how we store as JSON via JsonStorage, then load as a chararray to get the entire record as JSON. It would be more convenient to convert Pig bags and tuples to JSON directly. This would let us retain an ID field as key, and only JSONize our record for that key as a string.

ToJson to the Rescue!

That is precisely what the ToJson method of pig-to-json does. It takes a bag or tuple or nested combination thereof and returns a JSON string.

Our data looks like so:

emails: {message_id: chararray,
         date: chararray,
         from: (address: chararray,name: chararray),
         subject: chararray,
         body: chararray,
         tos: {ARRAY_ELEM: (address: chararray,name: chararray)},
         ccs: {ARRAY_ELEM: (address: chararray,name: chararray)},
         bccs: {ARRAY_ELEM: (address: chararray,name: chararray)}

We can JSONify bags:

emails = load '/me/Data/enron.avro' using AvroStorage();
emails = limit emails 10;
json_test = foreach emails generate message_id, com.hortonworks.pig.udf.ToJson(tos) as bag_json;
dump json_test

Which gets us JSON arrays of JSON objects:

(<735.1075840186524.JavaMail.evans@thyme>,[{"address":"","name":"Kam Keiser"},{"address":"","name":"Mike Grigsby"}])

We can JSONify tuples:

emails2 = load '/me/Data/enron.avro' using AvroStorage();
emails2 = limit emails2 10;
json_test2 = foreach emails2 generate message_id, com.hortonworks.pig.udf.ToJson(from) as tuple_json;
dump json_test2

Which gets us JSON objects:

(<167.1075851646300.JavaMail.evans@thyme>,{"address":"","name":"Jeff Dasovich"})
(<185.1075857304356.JavaMail.evans@thyme>,{"address":"","name":"Chris Dorland"})
(<735.1075840186524.JavaMail.evans@thyme>,{"address":"","name":"Phillip M. Love"})

And we can JSONify more complex, nested structures:

-- This works for arbitrarily complex data structures as well
a = foreach (group emails by from.address) generate group as from_address, COUNT_STAR(emails) as sent_count, FLATTEN(ema.tos) as tos;  
b = group a by from_address;
c = foreach b generate group as from_address, com.hortonworks.pig.udf.ToJson(a) as json_test;
store c into '/tmp/big_test_num';

Which gets us an array of JSON objects where one field refers to an array of other objects, and one field stores a number:	[{"tos":[{"address":"","name":null}],"sent_count":1,"from_address":""}]	[{"tos":[{"address":"","name":null}],"sent_count":1,"from_address":""}]	[{"tos":[{"address":"","name":null}],"sent_count":1,"from_address":""}]	[{"tos":[{"address":"","name":"Shena Cherian"}],"sent_count":1,"from_address":""}]	[{"tos":[{"address":"","name":null}],"sent_count":1,"from_address":""}]	[{"tos":[{"address":"","name":null}],"sent_count":1,"from_address":""}]

We are JSONizing fields like crazy. Its madness! Woohoo!

You can download the project on github here: To build it, you can:

ant clean; ant dist

ToJson Internals

Setting up a Pig EvalFunc project is easy. I copied my ivy.xml from some place, to import dependencies from maven:


I also copied my build.xml from some place too, and edited a few values to make it work with my class. The meat of the UDF is in, which I copied from some place else and edited. There’s an interesting bit here:

    public Schema outputSchema(Schema inputSchema) {

        // We must strip the outer {} or this schema won't parse on the back-end
        // This is a trick until PIG-2910 is fixed. Thanks to Thejas for this!
        String schemaString = inputSchema.toString().substring(1, inputSchema.toString().length() - 1);

        // Set the input schema for processing
        UDFContext context = UDFContext.getUDFContext();
        Properties udfProp = context.getUDFProperties(this.getClass());

        udfProp.setProperty("horton.json.udf.schema", schemaString);

        // Construct our output schema which is one field, that is a chararray
        return new Schema(new FieldSchema(null, DataType.CHARARRAY));

We use EvalFunc.outputSchema to pass our input’s schema from Pig’s front end to its distributed back-end using the UDFContext’s properties. Our output schema is always a chararray, as this is ToJson after all. We retrieve the input schema in our Evalfunc.exec method:

schema = Utils.getSchemaFromString(strSchema);
// Parse the schema from the string stored in the properties object.
Object field = input.get(0);
Object jsonObject = fieldToJson(field, schema.getFields().get(0));
String json = jsonObject.toString();
return json;

Pig UDFs are pretty easy to write, as you can see! Be lazy. Find an apache licensed pig UDF on github or in Piggybank and make it your own!


Leave a Reply

Your email address will not be published. Required fields are marked *

If you have specific technical questions, please post them in the Forums