Skip to content

JSON Lines

The JSON Lines format is a text format of newline-delimited JSON. In particular:

  1. The input must be UTF-8 encoded.
  2. Every line must be a valid JSON value.
  3. The line separator must be \n. As \r is silently ignored, \r\n is also supported.
  4. The final character may be \n, but is not required to be one.

JSON Text example

{"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]}
{"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]}
{"name": "May", "wins": []}
{"name": "Deloise", "wins": [["three of a kind", "5♣"]]}

JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used:

Example: Parse JSON Text input line by line

The example below demonstrates how JSON Lines can be processed.

#include <sstream>
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
    // JSON Lines (see
    std::stringstream input;
    input << R"({"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]}
{"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]}
{"name": "May", "wins": []}
{"name": "Deloise", "wins": [["three of a kind", "5♣"]]}

    std::string line;
    while (std::getline(input, line))
        std::cout << json::parse(line) << std::endl;


{"name":"Gilbert","wins":[["straight","7♣"],["one pair","10♥"]]}
{"name":"Alexa","wins":[["two pair","4♠"],["two pair","9♠"]]}
{"name":"Deloise","wins":[["three of a kind","5♣"]]}


Using operator>> like

json j;
while (input >> j)
    std::cout << j << std::endl;

with a JSON Lines input does not work, because the parser will try to parse one value after the last one.

Last update: July 28, 2022