ChatGPT解决这个技术问题 Extra ChatGPT

Are multi-line strings allowed in JSON?

Is it possible to have multi-line strings in JSON?

It's mostly for visual comfort so I suppose I can just turn word wrap on in my editor, but I'm just kinda curious.

I'm writing some data files in JSON format and would like to have some really long string values split over multiple lines. Using python's JSON module I get a whole lot of errors, whether I use \ or \n as an escape.

structure your data: break the multiline string into an array of strings, and then join them later on.
Try hjson tool. It will convert your multiline String in json to proper json-format.

N
Neuron

JSON does not allow real line-breaks. You need to replace all the line breaks with \n.

eg:

"first line second line"

can saved with:

"first line\nsecond line"

Note:

for Python, this should be written as:

"first line\\nsecond line"

where \\ is for escaping the backslash, otherwise python will treat \n as the control character "new line"


-1 The OP is using the "\n" escape sequence. It's not working because they're not escaping the backslash, as "\\n", so Python is converting the escape sequence to a newline character rather than leaving it as literally a backslash followed by an en, as JSON requires.
@user359996 I'm not sure that's true. For me (storing data in JSON with just \n and outputting it via Curses), \n seems to work okay. It depends on the view/rendering engine, it seems.
@Nawaz: "\n" and "\r" are escape sequences for linefeed and carriage return, respectively. They are not the literal linefeed and carriage-return control characters. As an additional example to make it more clear, consider that "\\" is an escape sequence for backslash, as opposed to a literal backslash. The JSON grammar explicitly excludes control characters (cf. the "char" definition), and instead provides for their representation via escape sequences (\\, \r, \n, etc.).
The OP didn't want to represent new lines but to format one logical JSON line over multiple source lines. He did muddy the waters by talking about \n. He wants what in the old days we called "continuation lines" pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap01/continue.html.
Doesn't answer the question.
M
Mark Adelsberger

Unfortunately many of the answers here address the question of how to put a newline character in the string data. The question is how to make the code look nicer by splitting the string value across multiple lines of code. (And even the answers that recognize this provide "solutions" that assume one is free to change the data representation, which in many cases one is not.)

And the worse news is, there is no good answer.

In many programming languages, even if they don't explicitly support splitting strings across lines, you can still use string concatenation to get the desired effect; and as long as the compiler isn't awful this is fine.

But json is not a programming language; it's just a data representation. You can't tell it to concatenate strings. Nor does its (fairly small) grammar include any facility for representing a string on multiple lines.

Short of devising a pre-processor of some kind (and I, for one, don't feel like effectively making up my own language to solve this issue), there isn't a general solution to this problem. IF you can change the data format, then you can substitute an array of strings. Otherwise, this is one of the numerous ways that json isn't designed for human-readability.


It is not clear what the OP wants, newlines in string, or organize string better...
@9ilsdx9rvj0lo : No, it's not.
This is the right answer that OP really wants, and SO DO ME, even the result sounds not very satisfying about JSON formatter...
Brilliant. This was the answer I was looking for, and moreover, the reminder that json is not a language was helpful to set the problem in context.
It's very clear what the OP is asking and this is the right answer.
A
Alexei Levenkov

I have had to do this for a small Node.js project and found this work-around to store multiline strings as array of lines to make it more human-readable (at a cost of extra code to convert them to string later):

{
 "modify_head": [

  "<script type='text/javascript'>",
  "<!--",
  "  function drawSomeText(id) {",
  "  var pjs = Processing.getInstanceById(id);",
  "  var text = document.getElementById('inputtext').value;",
  "  pjs.drawText(text);}",
  "-->",
  "</script>"

 ],

 "modify_body": [

  "<input type='text' id='inputtext'></input>",
  "<button onclick=drawSomeText('ExampleCanvas')></button>"
 
 ],
}

Once parsed, I just use myData.modify_head.join('\n') or myData.modify_head.join(), depending upon whether I want a line break after each string or not.

This looks quite neat to me, apart from that I have to use double quotes everywhere. Though otherwise, I could, perhaps, use YAML, but that has other pitfalls and is not supported natively.


This is a solution for a specific setting, not necessarily related to the question. What you create there are not multiline strings (which is not possible anyway), but arrays with strings inside
This shows how to insert newline in strings, which does NOT answer the question. This answer does.
fgrieu -- one could just as easily concatenate the strings without adding a newline. With that small alteration, it does provide a workaround for multiline strings (as long as you are in control of specifiying the JSON schema). I will try to improve the answer with this.
Thanks, I like this. I'm going with this for what I'm working on. It looks neat and organized. I'm going to have each new line in this array imply a line break in the outputted text, although this solution could also work for cases where you don't insert line breaks. I've used this solution before in my javascript source code just because I liked how organized it looks and how it doesn't leave any doubt as to what kinds of whitespace get into the final string.
Thanks, this solved my issue with having command line arguments on separate lines in my launch.json in VScode.
L
Lightness Races in Orbit

Check out the specification! The JSON grammar's char production can take the following values:

any-Unicode-character-except-"-or-\-or-control-character

\"

\\

\/

\b

\f

\n

\r

\t

\u four-hex-digits

Newlines are "control characters" so, no, you may not have a literal newline within your string. However you may encode it using whatever combination of \n and \r you require.


This is the correct answer as it leaves no ambiguity. New lines are allowed, per the specification, so long as they are properly escaped with the control character.
@AliKhaki \n in JSON will not accomplish the outcome sought by the question. Either you're thinking of something else (i.e. embedding newline characters), or you're talking about a newline in a string literal (containing JSON) in some programming language, which is again something different.
@LightnessRacesinOrbit yes i looking for newline in string
J
James Gentes

JSON doesn't allow breaking lines for readability.

Your best bet is to use an IDE that will line-wrap for you.


An editor like BBEdit that supports "soft" line wrap is ideal. It wraps the text so it all appears within the visible area of the editor window, but only the line endings that you type (e.g., hitting carriage return) are persisted in the file when it is saved. Makes it easier to edit JSON with really long strings without having to resort to code tricks or hacks.
Sometimes I think that the JSON format was not thoroughly designed. No comments, no multi-line support. I understand it is just a data format, but "to be used by humans". So some "human-friendly" features would be helpful.
Thanks for your answer, which made me smile. That is actually the only correct answer, because the JSON standard is very rigid here and therefore very long texts are difficult to maintain. Why didn't I come up with this simple solution myself? :-)
@dvdmn I totally agree. As it would design some 90 years old programmer who had his best times before the 1st moon landing.
Irony is not the best place for a learning platform, although I also needed to smile a short moment.
N
Neuron

This is a really old question, but I came across this on a search and I think I know the source of your problem.

JSON does not allow "real" newlines in its data; it can only have escaped newlines. See the answer from @YOU. According to the question, it looks like you attempted to escape line breaks in Python two ways: by using the line continuation character ("\") or by using "\n" as an escape.

But keep in mind: if you are using a string in python, special escaped characters ("\t", "\n") are translated into REAL control characters! The "\n" will be replaced with the ASCII control character representing a newline character, which is precisely the character that is illegal in JSON. (As for the line continuation character, it simply takes the newline out.)

So what you need to do is to prevent Python from escaping characters. You can do this by using a raw string (put r in front of the string, as in r"abc\ndef", or by including an extra slash in front of the newline ("abc\\ndef").

Both of the above will, instead of replacing "\n" with the real newline ASCII control character, will leave "\n" as two literal characters, which then JSON can interpret as a newline escape.


S
Sandip Nirmal

Write property value as a array of strings. Like example given over here https://gun.io/blog/multi-line-strings-in-json/. This will help.

We can always use array of strings for multiline strings like following.

{
    "singleLine": "Some singleline String",
    "multiline": ["Line one", "line Two", "Line Three"]
} 

And we can easily iterate array to display content in multi line fashion.


I would you suggest you add the information in your answer from the link, Because links can break in future.
But them you have an array, not a string. An array is not a string. Period.
Was just thinking of this. Nice!
Sure, it changes the format. But if the use of multistring is to have some kind of header at the beginning of a JSON file for documentation purposes, it works fine, and human readability is the most important aspect. It looks even better with some indent. pastebin.com/Rs8HSQH5
@BrandonStivers: Normally you can teach a machine new things, so he indeed can specify a format as array and saying that each array entry is a kind of new line. Then implement that in a program. Your remark is true for the moment and for a specific use cases the questioner simply did not ask for. Anyway, good hint in general - that proposed solution cannot be applied in all cases now.
c
ced-b

While not standard, I found that some of the JSON libraries have options to support multiline Strings. I am saying this with the caveat, that this will hurt your interoperability.

However in the specific scenario I ran into, I needed to make a config file that was only ever used by one system readable and manageable by humans. And opted for this solution in the end.

Here is how this works out on Java with Jackson:

JsonMapper mapper = JsonMapper.builder()
   .enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS)
   .build()

G
Gambitier

You can encode at client side and decode at server side. This will take care of \n and \t characters as well

e.g. I needed to send multiline xml through json

{
  "xml": "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiID8+CiAgPFN0cnVjdHVyZXM+CiAgICAgICA8aW5wdXRzPgogICAgICAgICAgICAgICAjIFRoaXMgcHJvZ3JhbSBhZGRzIHR3byBudW1iZXJzCgogICAgICAgICAgICAgICBudW0xID0gMS41CiAgICAgICAgICAgICAgIG51bTIgPSA2LjMKCiAgICAgICAgICAgICAgICMgQWRkIHR3byBudW1iZXJzCiAgICAgICAgICAgICAgIHN1bSA9IG51bTEgKyBudW0yCgogICAgICAgICAgICAgICAjIERpc3BsYXkgdGhlIHN1bQogICAgICAgICAgICAgICBwcmludCgnVGhlIHN1bSBvZiB7MH0gYW5kIHsxfSBpcyB7Mn0nLmZvcm1hdChudW0xLCBudW0yLCBzdW0pKQogICAgICAgPC9pbnB1dHM+CiAgPC9TdHJ1Y3R1cmVzPg=="
}

then decode it on server side

public class XMLInput
{
        public string xml { get; set; }
        public string DecodeBase64()
        {
            var valueBytes = System.Convert.FromBase64String(this.xml);
            return Encoding.UTF8.GetString(valueBytes);
        }
}

public async Task<string> PublishXMLAsync([FromBody] XMLInput xmlInput)
{
     string data = xmlInput.DecodeBase64();
}

once decoded you'll get your original xml

<?xml version="1.0" encoding="utf-8" ?>
  <Structures>
       <inputs>
               # This program adds two numbers

               num1 = 1.5
               num2 = 6.3

               # Add two numbers
               sum = num1 + num2

               # Display the sum
               print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
       </inputs>
  </Structures>

Y
Yoz

If it's just for presentation in your editor you may use ` instead of " or '

const obj = {
myMultiLineString: `This is written in a \
multiline way. \
The backside of it is that you \
can't use indentation on every new \
line because is would be included in \
your string. \
The backslash after each line escapes the carriage return. 
`
}

Examples:

console.log(`First line \
Second line`);

will put in console: First line Second line

console.log(`First line 
second line`);

will put in console: First line second line

Hope this answered your question.


M
Mukesh Kumar

Try this, it also handles the single quote which is failed to parse by JSON.parse() method and also supports the UTF-8 character code.

    parseJSON = function() {
        var data = {};
        var reader = new FileReader();
        reader.onload = function() {
            try {
                data = JSON.parse(reader.result.replace(/'/g, "\""));
            } catch (ex) {
                console.log('error' + ex);
            }
        };
        reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}

The question was asking if it's possible to have a multi-line string