Development Tip

JSON의 여러 줄 문자열

yourdevel 2020. 10. 3. 12:05
반응형

JSON의 여러 줄 문자열


일부 데이터 파일을 JSON 형식으로 작성 중이며 정말 긴 문자열 값을 여러 줄로 나누고 싶습니다. 파이썬의 JSON 모듈을 사용하면 내가 사용 \하든 \n이스케이프로 사용하든 많은 오류가 발생합니다 .

JSON에서 여러 줄 문자열을 사용할 수 있습니까? 대부분 시각적 인 편안함을위한 것이기 때문에 편집기에서 단어 줄 바꿈을 켤 수 있다고 생각하지만 조금 궁금합니다 ...


JSON 은 실제 줄 바꿈을 허용하지 않습니다. 모든 줄 바꿈을 \n.

예 :

"first line second line"

다음으로 저장할 수 있습니다.

"first line\nsecond line"

노트 :

Python경우 다음과 같이 작성해야합니다.

"first line\\nsecond line"

\\백 슬래시를 이스케이프 처리하는 위치 입니다. 그렇지 않으면 python이 \n제어 문자 "new line"으로 처리


작은 Node.js 프로젝트에 대해이 작업 을 수행해야했고이 해결 방법을 찾았습니다 .

{
 "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>"

 ],
}

이것은 나에게 아주 깔끔하게 보이며, 어디서나 큰 따옴표를 사용해야한다는 점에서 appart입니다. 그렇지 않으면 YAML을 사용할 수 있지만 다른 함정이 있으며 기본적으로 지원되지 않습니다. 구문 분석하면, 난 그냥 사용 myData.modify_head.join('\n')또는 myData.modify_head.join()I는 각 문자열 여부를 후 줄 바꿈을할지 여부에 따라.


사양을 확인하십시오 ! JSON 문법의 char 생성은 다음 값을 가질 수 있습니다.

  • 모든 유니 코드 문자 제외 "- \또는 - 또는 제어 문자
  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u 4 자리 16 진수

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.


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.


JSON doesn't allow breaking lines for readability.

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


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.


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.


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.


Use regex to replace all occurrences of \r\n with \\n.

This worked for me in scala.

val newstr = str.replace("\r\n", "\\n")

Use json5 (loader) see https://json5.org/ - example (by json5)

{
  lineBreaks: "Look, Mom! \
No \\n's!",
}

If you are willing to use Node.js, you can do this:

module.exports = {

  multilineStr: `

     dis my life 
     it's now or never

  `

}

you can import with Node.js and convert it to JSON easily like so:

echo `node -pe 'JSON.stringify(require("./json-mod.js"))'`

and you get:

{"multilineStr":"\n \n dis my life\n it's now or never\n \n "}

how it works: you use Node.js to load a JS module, which creates a JS object which can easily be JSON stringified by Node.js. The -e option evaluates the string, and the -p option echoes the return result of the last Node.js operation to stdout.

If you want to load a .js script that's in a different working directory, you have to switch the "" and '' strings:

my_script='../json-mod.js'
echo `node -pe "JSON.stringify(require('$my_script'))"`

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.


put the multiline text on txt file and then

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

(it work's on mongoDB)

참고URL : https://stackoverflow.com/questions/2392766/multiline-strings-in-json

반응형