DEV Community

Swastik Baranwal
Swastik Baranwal

Posted on

What is JSON? Why to use it?

Can anyone explain me what is JSON and why to use JSON and is it better than XML or it depends upon the work being done?

Top comments (1)

ahferroin7 profile image
Austin S. Hemmelgarn

JSON is a data serialization format derived from JavaScript's object literal syntax (which happens to look like the object/dictionary/map syntax from many other programming languages).

The original idea was that because it's also valid JS code (except it might not be, there are differences in the official spec), you could just use the exec() function to load it in JS. This is no longer the recommended way to use it (for multiple reasons), but JSON has a number of other benefits:

  • It's compact. In almost all cases, the JSON representation of some data will be smaller (often significantly so) than the equivalent XML serilaization.
  • It's technically safer than XML. Because of how XML works, parsing is complicated and very easy to get wrong, possibly leading to disastrous consequences (entity expansion being one of the big issues here, as it can be used to effect DoS attacks pretty easily if the parser doesn't limit it sanely). JSON is much simpler, and therefore easier to parse safely.
  • It's portable. More so than XML in fact, as there are more languages these days that have JSON support included than XML support. The above mentioned simplicity also means that JSON is easy enough to parse that you can do it with far fewer resources, making it more suitable for systems that have very limited memory or processing power.
  • It doesn't differentiate between tags and attributes. JSON has no concept of tags, everything is functionally an attribute, and attributes can have any valid data type for their values, including objects and arrays. One of the hard parts of using XML (or any SGML-derived language) efficiently is figuring out what should be an attribute, and what should be a tag. JSON quite simply doesn't have that issue.
  • It's easier for people to read than XML. As mentioned above, JSON looks very much like standard object/dictionary/map syntax from many widely used programming languages. As a result, most programmers can read it easily at a glance, even if they've never seen it before. In comparison, XML looks nothing like constructs used in most languages, so it takes more effort to understand it.

Note, there are other options than JSON if you want to serialize data. YAML is rather popular too (it goes even further than JSON in terms of readability, but loses some of the simplicity of parsing in exchange for this), and many languages have some 'native' data serialization format (Python has it's pickle module, Erlang and Elixir have ETF, etc). JSON is good for interoperability when you need to talk between two software components, but there are better options in some cases.