How to Represent Multiline Strings in Valid JSON

JSON has no multiline string syntax. Learn how to escape line breaks as \n, generate the result with jq, Python or JavaScript, and verify that the text survives intact.

JSON has no special syntax for multiline strings. A string value must sit inside one pair of double quotes with no raw line breaks. Line breaks in the text are written as escape sequences, and the parser turns them back into real line breaks when it reads the data. This guide explains the rule, shows how to generate correctly escaped JSON from multiline text, and shows how to confirm that nothing in the text changed along the way.

What a Multiline Value Looks Like in JSON

The JSON standard (RFC 8259) requires every control character from U+0000 through U+001F to be escaped when it appears inside a string. The line feed (U+000A), the carriage return (U+000D) and the tab (U+0009) are all in that range. If you press Enter inside a quoted value, the file is no longer valid JSON. This example is rejected by a strict parser:

{
  "message": "First line
Second line"
}

The valid form keeps the value on one physical line. It uses the two-character sequence backslash plus n wherever a line break belongs:

{
  "message": "First line\nSecond line"
}

When a program parses this, the value of message contains two lines separated by a real line feed. These are the escape sequences JSON defines:

  • \n — line feed (LF, U+000A), the usual newline on Linux and macOS
  • \r — carriage return (CR, U+000D); Windows-style line endings appear as \r\n
  • \t — tab (U+0009); a literal tab character inside a string is also invalid
  • " — a double quote inside the string
  • \ — a literal backslash
  • \uXXXX — any character by its four-digit hexadecimal code; for example, \u000A is the same line feed as \n
  • \b, \f and / — backspace, form feed and an optionally escaped forward slash

Several familiar multiline tricks are not valid JSON. These include backtick strings, triple quotes, joining strings with a plus sign, and ending a line with a backslash to continue it. Some related formats, such as JSON5 and YAML, offer multiline syntax, but a standard JSON parser rejects it.

Alternative: Store the Text as an Array of Lines

If people will edit the file by hand, a list of lines can be easier to read than one long escaped string:

{
  "message": [
    "First line",
    "Second line"
  ]
}

The trade-off is that the program reading the file must join the lines itself, and it has to choose which line ending to use. The array form also cannot record whether the original text ended with a newline or used CRLF line endings. Use an escaped string when the exact characters matter, such as a key file, an email body or a code snippet. Consider an array when the content is configuration that humans maintain line by line.

How to Produce the Escaped String

Before you start, have the original text in a file or a variable and know two things about it:

  • Its line endings: LF only, or CRLF.
  • Its encoding: JSON exchanged between systems is expected to be UTF-8.

Avoid escaping by hand or with find-and-replace. Quotes, backslashes and tabs must be escaped along with the line breaks, and backslashes must be handled first. A JSON library or tool gets all of this right in one pass. The commands below follow the documented behavior of jq, Python's json module and JavaScript's JSON object. The outputs shown are examples, not results captured from a test run, so check them against your own data with the steps in the next section.

Option 1: jq on the Command Line

The -R option makes jq read raw text instead of JSON. The -s option reads all of the input into a single string. Together, they wrap a whole text file into one JSON string value. Write the output to a new file, never to the input file.

jq -Rs '{message: .}' notes.txt > notes.json

Example input: the file notes.txt below has three lines and ends with a newline. The third line begins with a tab character, which is invisible here but appears as \t in the output.

First line
Second line with "quotes"
	Indented with a tab

Expected notes.json (example):

{
  "message": "First line\nSecond line with \"quotes\"\n\tIndented with a tab\n"
}

Two newline details change the result. First, the file's final newline becomes a trailing \n in the value. Second, a file saved with Windows line endings produces \r\n instead of \n. If you want neither, adjust the filter. Keep in mind that either change means the JSON no longer matches the file byte for byte.

# drop one trailing newline
jq -Rs '{message: rtrimstr("\n")}' notes.txt > notes.json

# convert CRLF line endings to LF
jq -Rs '{message: gsub("\r\n"; "\n")}' notes.txt > notes.json

Option 2: Python

json.dumps converts a Python string into a JSON string and escapes line breaks, quotes, backslashes and tabs automatically:

import json

text = "First line\nSecond line with \"quotes\"\n\tIndented with a tab"
print(json.dumps({"message": text}))

Expected output (example):

{"message": "First line\nSecond line with \"quotes\"\n\tIndented with a tab"}

When you read the text from a file, keep these defaults in mind:

  • Python's default text mode translates CRLF to LF on read. Open the file with newline="" to keep the original line endings.
  • By default, json.dumps also escapes every non-ASCII character as \uXXXX. Both forms are valid JSON. Pass ensure_ascii=False if you want accented letters and other symbols to stay readable.
import json

with open("notes.txt", encoding="utf-8", newline="") as src:
    text = src.read()

with open("notes.json", "w", encoding="utf-8") as out:
    json.dump({"message": text}, out, ensure_ascii=False, indent=2)

Option 3: JavaScript

In JavaScript, a template literal can hold real line breaks, and JSON.stringify escapes them when it serializes the value:

const text = `First line
Second line with "quotes"`;
console.log(JSON.stringify({ message: text }));
// example output: {"message":"First line\nSecond line with \"quotes\""}

Calling JSON.stringify(value, null, 2) indents the object structure. Line breaks inside string values stay escaped as \n either way.

How to Check the Result

  • 1. Validate the syntax. Run jq empty notes.json, which prints nothing and exits successfully when the file is valid. Alternatively, run python3 -m json.tool notes.json. Either command reports an error for raw line breaks or unescaped quotes.
  • 2. Round-trip the value. Extract the string and confirm it matches the source text exactly. Use the commands below.
  • 3. Read the output correctly. Formatters and pretty-printers display \n inside strings rather than breaking the line. That is correct behavior. The line breaks only become real when the value is parsed and printed as raw text, for example with jq -r '.message' notes.json.
# jq: -j prints the raw value without adding a newline
jq -j '.message' notes.json | cmp - notes.txt && echo identical
import json

with open("notes.txt", encoding="utf-8", newline="") as src:
    original = src.read()
with open("notes.json", encoding="utf-8") as f:
    restored = json.load(f)["message"]
print(restored == original)

The round-trip comparison only passes if you kept the text unchanged. If you trimmed the trailing newline or converted CRLF to LF on purpose, expect a difference, and confirm it is the only one.

Common Problems and Their Fixes

  • Invalid or bad control character errors: a raw line break or tab sits inside a string. The exact wording varies by parser. Regenerate the file with a JSON tool instead of pasting text between quotes.
  • A visible backslash-n after parsing: the text was escaped twice, so the file contains \n. This usually happens when already-escaped text is passed through a JSON encoder again. Encode the raw text exactly once.
  • Changed line endings: CRLF became LF, or the reverse, because a tool or file mode translated newlines. Use the newline-preserving options shown above and verify with a byte-level comparison.
  • Lenient parsing that hides the problem: Python's json.loads accepts raw control characters if you pass strict=False. The file is still not valid JSON, so other parsers will reject it.

Keep the Original Text Safe

Never redirect a command's output to the same file it reads. The shell empties the target file before the tool starts, so a command like jq -Rs . notes.txt > notes.txt destroys the original. Write to a new file, run the validation and round-trip checks, and only then replace or delete anything. If a JSON file is all you have left, you can recover the original text with jq -j '.message' notes.json > restored.txt, as long as the value was encoded only once.