Multiline strings in JSON

2018-12-31 16:25发布

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...

19条回答
谁念西风独自凉
2楼-- · 2018-12-31 17: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);
查看更多
冷夜・残月
3楼-- · 2018-12-31 17:16

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

查看更多
大哥的爱人
4楼-- · 2018-12-31 17:16

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.

查看更多
其实,你不懂
5楼-- · 2018-12-31 17:16

You can try place <div></div>between sentences.

查看更多
爱死公子算了
6楼-- · 2018-12-31 17:17
fieldval = rs.getString(rs.getMetaData().getColumnName(i))
  .trim()
  .replace("\\", "/")
  .replace("\r\n", "\\n")
  .replace("''", "\\n")
  .replace("\"", "\\n");
查看更多
刘海飞了
7楼-- · 2018-12-31 17:17

put the multiline text on txt file and then

var str = {
    text: cat('path_to_file/text.txt')
}

(it work's on mongoDB)

查看更多
登录 后发表回答