可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
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...
回答1:
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
, should written as:
\"first line\\\\nsecond line\"
which \\\\
is for escape backslash, otherwise python will treat \\n
as control character: new line
回答2:
I have had to do this for a small Node.js project and found this work-around:
{
\"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>\"
],
}
This looks quite neat to me, appart 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. 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.
回答3:
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.
回答4:
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, above. 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.
回答5:
JSON doesn\'t allow breaking lines for readability.
Your best bet is to use an IDE that will line-wrap for you.
回答6:
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.
回答7:
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.
回答8:
Is it possible to have multi-line strings in JSON?
Yes. I just tested this now with my Firefox web browser by pressing F12, clicking console and typing at the bottom of the screen.
x={text:\"hello\\nworld\"}
Object x has just been created from a JSON format string containing a multi-line string.
console.log(x.text)
hello
world
x.text is displayed showing that it is a multi-line string.
These two tests show that Firefox\'s Javascript interpreter is happy to create and use JSON with multiline strings.
More tests with JSON.stringify
and JSON.parse
showed the Javascript interpreter can convert an object containing multiline strings to JSON and parse it back again with no problem at all.
I have in the past stored the complete works of Shakespeare as a property in a JSON object and then sent it over the internet, uncorrupted.
Example
Here is a two line string entered over three lines
x={text:\"expert\\
s\\nex\\
change\"}
We can display the object
console.log(x)
giving
Object { text: \"experts\\nexchange\" }
or the string
console.log(x.text)
giving
experts
exchange
The end of lines in the string result from using \\n
and the multiple input lines are achieved using just \\ at the end of the line.
In practice you might want to synchronize your line endings with the ones in the string, e.g.
x={text:\"experts\\n\\
exchange\"}
Multi-Line String Length
console.log(\"Hello\\nWorld\".length)
11
console.log(\"Hello World\".length)
11
Note that the string with the newline is not longer than the string with the space. Even though two characters were typed on the keyboard (\'\\\' and \'n\'), only one character is stored in the string.
回答9:
Use regex to replace all occurrences of \\r\\n
with \\\\n
.
This worked for me in scala.
val newstr = str.replace(\"\\r\\n\", \"\\\\n\")
回答10:
Use json5 (loader) see https://json5.org/ - example (by json5)
{
lineBreaks: \"Look, Mom! \\
No \\n\'s!\",
}
回答11:
for multiline i\'m using:
singleline: \'value\',
singleline: \"value\",
multiline: ```
line 1
line 2
```
回答12:
{{name}}
{{name1}}
my.opt.push({\'name\':\'line1\',\'name1\':\'line2\')
回答13:
you could simply run the code below with your desire multiline string between tilde ~
character:
var multiLineString = `
this
is
the
multiline
String
`;
JSON.stringify(multiLineString);
回答14:
Try using base64
encoded string value. Worked for me most of the time.
{
\"singleLine\": \"Some singleline String\",
\"multiline\": [\"Line one\", \"line Two\", \"Line Three\"]
}
after base64
encoded string look like
{
\"singleLine\": \"Some singleline String\",
\"multiline\": \"TGluZSBvbmUKTGluZSBUd28KTGluZSBUaHJlZQ==\"
}
base64 encoding and decoding is available in all languages.
回答15:
fieldval = rs.getString(rs.getMetaData().getColumnName(i))
.trim()
.replace(\"\\\\\", \"/\")
.replace(\"\\r\\n\", \"\\\\n\")
.replace(\"\'\'\", \"\\\\n\")
.replace(\"\\\"\", \"\\\\n\");
回答16:
Just include paragraph tags to make it look neat and more efficient.
Example:
\"body\": \"
Paragraph 1 here.
Paragraph 2 here.
\",
回答17:
write any text in notepad++ with multi multi line
then press ctl+a and ctl+j to arrange them in one line
In json file write :
{
\"key\":\"multi line copied from notepad++\"
}
回答18:
put the multiline text on txt file and then
var str = {
text: cat(\'path_to_file/text.txt\')
}
(it work\'s on mongoDB)
回答19:
You can try place <div></div>
between sentences.