JSON


JavaScript Object Notation

About JSON

Using the nlohmann-json library from JSON for Modern C++ - Niels Lohmann.

JSON

Modern C++ refers to versions of the C++ language from C++11 onwards, continuing its evolution as a derivative language that extends C. The standards from C++11 onwards have significantly improved the way programs are written and their functionality, leading to what is now called Modern C++. New standards are introduced every three years, including C++11, C++14, C++17, C++20, and C++23.

Among the popular JSON libraries written in Modern C++, nlohmann/json stands out. This header-only open-source library has become trendy in recent years, offering multiple functions while maintaining stability and a proven track record. It is incredibly convenient in practice. Although its slower processing speed is often mentioned, its usability outweighs this drawback.


Data Formats

JSON files are text data saved in UTF-8 format, written according to a specific data description format.

Before the advent of JSON, CSV and XML were also used as data exchange formats. CSV has ambiguous specifications with no unified standards and poor data readability, while XML, though unified and highly flexible through markup language notation, suffers from slow parsing and larger data volume due to its tagged structure.

JSON offers high readability, minimal redundant information, and smaller data size compared to XML. It supports more data types than CSV, including strings, numbers, booleans, null, arrays, and objects.


Comparison

Animals Sounds Legs
Cat Meow 4
Dog Woof 4
Owl hoo-h’HOO-hoo-hoo 2

Describe the table above in CSV, XML, and JSON formats respectively.

FORMAT
Animals,Sounds,Legs
Cat,Meow,4
Dog,Woof,4
Owl,hoo-h'HOO-hoo-hoo,2
<?xml version="1.0" encoding="utf-8"?>
<Animals>
    <Animal Type="Cat" Sounds="Meow" Legs="4" />
    <Animal Type="Dog" Sounds="Woof" Legs="4" />
    <Animal Type="Owl" Sounds="hoo-h'HOO-hoo-hoo" Legs="2" />
</Animals>
{
    "ANIMALS":["Cat", "Dog", "Owl"],
    "SOUNDS":["Meow","Woof","hoo-h’HOO-hoo-hoo"],
    "LEGS":  [4,4,2]
}

For small data, CSV suffices, but JSON naturally describes data structures that CSV could not represent with its notation.

In XML, it is important to distinguish each entity with individual tags, and the redundancy of XML notation serves to enhance data consistency and readability. Therefore, it cannot be omitted, resulting in increased data volume.

For the keywords “animal,” “sound,” and “number of legs,” three data sets are included in an array:

  • Animals = Cat, Dog, Owl
  • Sounds = Meow, Woof, hoo-h’HOO-hoo-hoo
  • Legs = 4, 4, 2

The role of the nlohmann/json library is to parse this into a dictionary-type data structure so it can be used in C++.


Relevance URL