This commit is contained in:
nlohmann committed 2026-11-10 06:10:03 +00:00
1 parent eeea067a72
commit 8ddeea7128
18 files changed
+452 -439

No files matched your search

+1 -1
View File
@@ -26,7 +26,7 @@ json read_json_file(const std::string& path)
```
- **Check that the file is open.** A stream that failed to open looks like an empty input, so `parse` reports [`parse_error.101`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error101) ("unexpected end of input") at line 1, column 1 instead of saying that the file is missing. A relative path is resolved against the working directory of the running program, which is often not the directory of the source file (see the [FAQ](https://json.nlohmann.me/home/faq/#parsing-a-file-fails-with-unexpected-end-of-input)).
- **Don't read the file into a string first.** Parsing from a `std::ifstream` is only about 10 to 20 % slower than reading the whole file into a string with one `read()` and parsing that, and it needs no memory for the copy (see [input sources and performance](https://json.nlohmann.me/features/parsing/#input-sources-and-performance)). The common way to read a file with `std::istreambuf_iterator<char>` is so slow that it takes about twice as long as parsing from the stream. Read the file into a string only if you need the text itself, for example for an error message. This advice is for `json::parse`. [`json_document`](https://json.nlohmann.me/features/json_view/index.md) reads a stream into a buffer that it owns anyway, so there is no copy to save: reading the file into a `std::string` yourself and passing that as an lvalue, which the document borrows, was about 6 to 12 % faster than parsing from the stream, with the same single buffer.
- **Read the file into a string only if the memory is no concern.** Parsing from a `std::ifstream` takes about 1.15 to 1.45 times as long as reading the whole file into a string with one `read()` and parsing that, but it needs no memory for the copy (see [input sources and performance](https://json.nlohmann.me/features/parsing/#input-sources-and-performance)). The common way to read a file with `std::istreambuf_iterator<char>` is so slow that it takes about twice as long as parsing from the stream. This advice is for `json::parse`. [`json_document`](https://json.nlohmann.me/features/json_view/index.md) reads a stream into a buffer that it owns anyway, so there is no copy to save: reading the file into a `std::string` yourself and passing that as an lvalue, which the document borrows, was about 6 to 12 % faster than parsing from the stream, with the same single buffer.
- `parse` requires the file to hold exactly one JSON value. Files with one value per line are read with [JSON Lines](https://json.nlohmann.me/features/parsing/json_lines/index.md); files too large for memory are covered in [Large, streamed, and partial input](https://json.nlohmann.me/features/parsing/large_and_partial_input/index.md).
## Writing a JSON file