JSON is a new human readable data format that has become very popular in the last few years, especially in web development.
JSON is very similar to XML. They both try to solve the same problem by creating a simple, human readable format for storing data. Up until recently, XML was used for any type of system that needed to send small portions of data quickly without a database attached. Think API calls that ask for information from the server. For the most part, XML does the job just fine. So what’ the need for JSON?
JSON is claimed to have many benefits over XML, including:
- “Easier” to read
- Faster to parse
- Takes up less space
Although “‘easier’ to read” is a point that’s difficult to measure, the other two points are not.
It’s very easy to see that JSON does indeed require less space to store the same information. After a quick look on the JSON website, you can find several examples that compare the two formats. Just by looking at the page, it’s easy to determine that the JSON representation takes far less characters to describe than its XML counterpart. For instance, the first example (a glossary data structure) requires 502 characters in XML, while only 345 characters in JSON (about 30 % less space).
Now for the “faster to parse” point, which is a bit harder to really test. For this point, I wrote up a quick test to determine how fast I could parse a XML and JSON string into a Java object.
For XML parsing, I used the build in SAX Parser. The SAX Parser allows me to iterate through the XML file and assign XML values to the appropriate value in the object. This method is a bit more cumbersome than what I used for JSON parsing, but certainly not unreasonable.
For JSON parsing, I loaded up the GSON library, which easily converts between JSON and java objects with just a one liner. All that was needed was the class definition itself (i.e. the Book class with properly named fields). This does, however, couple the class variables to the JSON instance. If either the class instance names change, or the JSON field names change, problems will arise.
To begin, I took a fairly simple data structure and created a XML and JSON representation of it. The following two XML and JSON files were created using information from Programming Pearls.
The parsing test was run on both the above XML and JSON files 10,000,000 times. The results are not surprising. JSON is parsed and converted into a Java object about 30% faster than XML.
- Average JSON Run time: 3.647208974029518E-5
- Average XML Run time: 5.011537916910817E-5
My findings are that JSON runs 30% faster and takes up 30% less space than XML. These results seem to be in line with what much of the development community believes in regards to the two formats. The switch to JSON for data handling can net a fairly large increase in performance, while also reducing the amount of space required.