JSON是否允许多行字符串?

发布于 2025-01-27 04:20:44 字数 172 浏览 2 评论 0 原文

JSON是否可以使用多行字符串?

这主要是为了视觉舒适,所以我想我可以在编辑中打开文字包装,但我有点奇怪。

我正在以JSON格式编写一些数据文件,并希望将一些非常长的字符串值分为多行。无论我使用 \ \ \ n 作为逃生,使用Python的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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

橘味果▽酱 2025-02-03 04:20:44

不幸的是,这里的许多答案都解决了如何在字符串数据中放置newline字符的问题。问题是如何通过将字符串值跨多行代码分配,使代码看起来更好。 (即使是识别此的答案,也提供了假定一个人可以自由更改数据表示形式的“解决方案”,在许多情况下,这不是。)

更糟糕的消息是,没有一个好的答案。

在许多编程语言中,即使它们不明确支持跨线的分裂字符串,您仍然可以使用字符串串联来获得所需的效果;而且,只要编译器不糟糕,就可以了。

但是JSON不是编程语言。这只是一个数据表示。您不能告诉它是连接弦的。它的语法(相当小)也不包括任何用于在多行上表示字符串的设施。

没有设计某种前处理器(我,我不想有效地编造我自己的语言来解决这个问题),因此没有一般的解决方案解决这个问题。如果您可以更改数据格式,则可以替换一系列字符串。否则,这是JSON并非为人类可读性设计的众多方式之一。

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.

画骨成沙 2025-02-03 04:20:44

json 不允许真正的线路breaks。您需要用 \ n 替换所有线路休息。

例如:

"first line
second line"

可以保存:

“第一行\ nsecond Line”

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

eg:

"first line
second line"

can be saved with:

"first line\nsecond line"

烟燃烟灭 2025-02-03 04:20:44

我必须为一个小节点项目做到这一点他们稍后再串):

{
 "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>"
 
 ],
}

一旦解析,我只使用 mydata.modify_head.join('\ n') mydata.modify_head.join()是否需要在每个字符串之后休息。

除此之外,这对我来说很整洁,我必须在各地使用双引号。虽然否则,我也许可以使用YAML,但这还有其他陷阱,并且不受本地的支持。

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.

迟到的我 2025-02-03 04:20:44

查看规格! JSON Grammar的 char 生产可以采用以下值:

  • any-unicode-character-except- -or- \ code> \ -or -control-character
  • \ \“
  • \\
  • \/code>
  • \ b
  • \ f < \ f < /code>
  • \ n
  • \ r
  • \ t
  • \ u 四hex digits

新线是“控制字符”,因此,不,您的字符串中可能没有字面的新线。但是,您可以使用 \ n \ r 的任何组合进行编码。

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.

紫瑟鸿黎 2025-02-03 04:20:44

JSON不允许断路线以实现可读性。

您最好的选择是使用将为您固定的IDE。

JSON doesn't allow breaking lines for readability.

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

眼角的笑意。 2025-02-03 04:20:44

这是一个非常古老的问题,但是我在搜索中遇到了这个问题,我想我知道您的问题的根源。

JSON在其数据中不允许“真正的”新线;它只能逃脱新线。请参阅答案来自。根据这个问题,看起来您试图以两种方式逃脱线路断裂:通过使用行持续字符(“ \” )或使用“ \ n” 作为逃脱。

但是请记住:如果您在Python中使用字符串,则将特殊的ESC符号(“ \ t” “ \ n” )转换为真实的控制字符! “ \ n” 将被代表Newline字符的ASCII控件字符替换,这正是JSON中非法的字符。 (至于行延续字符,它只是将新线取出。)

因此,您需要做的就是防止Python逃脱字符。您可以使用RAW字符串(在字符串前面使用 r ,如 r“ abc \ ndef” ,或在其前面包含一个额外的斜线, newline(“ ABC \\ ndef”

。 >“ \ n” 作为两个字面字符,然后JSON可以将其解释为Newline逃生。

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.

忱杏 2025-02-03 04:20:44

将属性值写为字符串数组。就像这里给出的示例 https://gun.io/blog/blog/multi-line-line-line-srings-ing-in-sin--in-sin--in-sin--in-multi-line-ing-in-sin--in-mult-line-ing-in-sin--in-sin-sin-sin-sin-sin-sin-sin-sin-sin-sin-sin--in-string,-in- JSON/。这将有所帮助。

我们始终可以将字符串数组用于以下的多行字符串。

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

而且,我们可以轻松迭代数组以以多线方式显示内容。

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.

失眠症患者 2025-02-03 04:20:44

这是一个非常古老的问题,但是当我想提高使用复杂的管道表达式的Vega JSON规范代码的可读性时,我也有同样的问题。代码就像 this

AS 这个答案说,JSON不是为人类设计的。我了解这是一个历史决定,对于数据交换目的而言,这是有意义的。但是,JSON仍被用作此类情况的源代码。因此,我要求我们的工程师使用 hjson 用于源代码并将其处理给JSON。

例如,在Windows环境中的Git中,
您可以下载HJSON CLI二进制文件,并将其放入GIT/BIN目录中。
然后,将(transpile)HJSON源转换为JSON。使用自动化工具(例如Make)对于生成JSON将是有用的。

$ which hjson
/c/Program Files/git/bin/hjson

$ cat example.hjson
{
  md:
    '''
    First line.
    Second line.
      This line is indented by two spaces.
    '''
}

$ hjson -j example.hjson > example.json

$ cat example.json
{
  "md": "First line.\nSecond line.\n  This line is indented by two spaces."
}

如果在编程语言中使用转换的JSON,则语言特定的库,例如 hjson-js 有用。

我注意到相同的想法是在一个重复的问题中发布的,但我会分享更多信息。

This is a very old question, but I had the same question when I wanted to improve readability of our Vega JSON Specification code which uses complex conditoinal expressions. The code is like this.

As this answer says, JSON is not designed for human. I understand that is a historical decision and it makes sense for data exchange purposes. However, JSON is still used as source code for such cases. So I asked our engineers to use Hjson for source code and process it to JSON.

For example, in Git for Windows environment,
you can download the Hjson cli binary and put it in git/bin directory to use.
Then, convert (transpile) Hjson source to JSON. To use automation tools such as Make will be useful to generate JSON.

$ which hjson
/c/Program Files/git/bin/hjson

$ cat example.hjson
{
  md:
    '''
    First line.
    Second line.
      This line is indented by two spaces.
    '''
}

$ hjson -j example.hjson > example.json

$ cat example.json
{
  "md": "First line.\nSecond line.\n  This line is indented by two spaces."
}

In case of using the transformed JSON in programming languages, language-specific libraries like hjson-js will be useful.

I noticed the same idea was posted in a duplicated question but I would share a bit more information.

梦幻之岛 2025-02-03 04:20:44

虽然不是标准的,但我发现一些JSON库有支持多行字符串的选项。我说的是警告,这会损害您的互操作性。

但是,在我遇到的具体情况下,我需要制作一个仅由一个系统可读取且可以由人类管理的系统。最后选择了该解决方案。

这是使用 Jackson 在Java上奏效的:

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

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()
可是我不能没有你 2025-02-03 04:20:44

假设问题与易于编辑文本文件有关,然后手动将它们转换为JSON,我发现有两个解决方案:

  1. this 上一个答案),在这种情况下,您可以将现有的JSON文件转换为HJSON格式通过执行 hjson source.json&gt; target.hjson ,在您喜欢的编辑器中进行编辑,然后转换回JSON hjson -j target.hjson&gt; source.json 。您可以下载二进制在这里或使用在线转换在这里
  2. jsonnet ,但使用略有不同的格式(单个和双引号的字符串可以简单地跨度跨度跨度多个线)。方便地,主页具有可编辑的输入字段,因此您可以将多行JSON/JSONNET文件插入到其中,然后将它们立即在线转换为标准JSON。请注意,JSONNET支持更多用于模板JSON文件的好处,因此根据您的需求,研究可能很有用。

Assuming the question has to do with easily editing text files and then manually converting them to json, there are two solutions I found:

  1. hjson (that was mentioned in this previous answer), in which case you can convert your existing json file to hjson format by executing hjson source.json > target.hjson, edit in your favorite editor, and convert back to json hjson -j target.hjson > source.json. You can download the binary here or use the online conversion here.
  2. jsonnet, which does the same, but with a slightly different format (single and double quoted strings are simply allowed to span multiple lines). Conveniently, the homepage has editable input fields so you can simply insert your multiple line json/jsonnet files there and they will be converted online to standard json immediately. Note that jsonnet supports much more goodies for templating json files, so it may be useful to look into, depending on your needs.
合约呢 2025-02-03 04:20:44

您可以在客户端进行编码,并在服务器端进行解码。这也将照顾\ n和\ t字符,

例如我需要通过JSON发送多行XML,

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

然后在解码后在服务器端进行解码,

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();
}

您将获得原始的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>

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>
森林散布 2025-02-03 04:20:44

OP问的原因是我在这里最终出现的原因相同。有一个带有长文本的JSON文件。

在VS代码中,它只是 alt + z 打开JSON文件中的单词包装。如果您真正想要的只是将文件内容阅读为开发人员,那么更改实际数据并不是您想要的。

The reason OP asked is the same reason I ended up here. Had a json file with long text.

In VS Code it's just ALT+Z to turn on word wrapping in a json file. Changing the actual data isn't what you want, if all you really want is to read the contents of the file as a developer.

千柳 2025-02-03 04:20:44

我需要从我的错误日志中读取最后的 n 行号(使用nodejs),其内容看起来像这样:

{"environment":"development","level":"ERROR","message":"[08-03-2024 16:10:00] | Request failed |......"}
{"environment":"development","level":"ERROR","message":"[08-03-2024 16:10:51] | Request failed |......"}
{"environment":"development","level":"ERROR","message":"[08-03-2024 16:13:14] | Request failed |......"}

没有可靠的方法来读取此内容并使用Regex使用Regex删除/破坏/转换它然后将其映射到可读的格式。即使正如其他人所说的那样,JSON不可能有“看起来很漂亮”的线路休息。我唯一可以依靠的是日志文件中的每一行都以 \ n 结束,并且此 \ n 是在任何给定的行中唯一出现的。

无论如何,最终做了这样的事情:

const pathToLogs = path.join('path', 'to', 'error.log');
const result = {};
require('child_process').execSync(pathToLogs)
    .toString()
    .split('\n')
    .forEach((line, index) => {
        if (line) {
            result[index + 1] = line;
        }
    });

最终在Postman中看起来像这样的东西:

{
    "result": {
        "1": "{\"environment\":\"development\",\"level\":\"ERROR\",\"message\":\"[08-03-2024 16:10:51] | Request failed |.....",
        "2": "{\"environment\":\"development\",\"level\":\"ERROR\",\"message\":\"[08-03-2024 16:13:14] | Request failed |.....",
        "3": "{\"environment\":\"development\",\"level\":\"ERROR\",\"message\":\"[08-03-2024 16:17:10] | Request failed |....."
    }
}

不是最好的解决方案,但对我来说足够了。

I needed to read the last n number of lines (using NodeJS) from my error log, the contents of which looked something like this:

{"environment":"development","level":"ERROR","message":"[08-03-2024 16:10:00] | Request failed |......"}
{"environment":"development","level":"ERROR","message":"[08-03-2024 16:10:51] | Request failed |......"}
{"environment":"development","level":"ERROR","message":"[08-03-2024 16:13:14] | Request failed |......"}

There was no reliable way to read this and break/transform it using regex and then map it out to a readable format. And even if there was, as others have said, it's not possible for JSON to have line breaks to "look pretty". The only thing I can rely on is that each row in the log file ends with an \n and that this \n is the only occurrence of itself in any given row.

Anyway, ended up doing something like this:

const pathToLogs = path.join('path', 'to', 'error.log');
const result = {};
require('child_process').execSync(pathToLogs)
    .toString()
    .split('\n')
    .forEach((line, index) => {
        if (line) {
            result[index + 1] = line;
        }
    });

Ended up looking something like this in Postman:

{
    "result": {
        "1": "{\"environment\":\"development\",\"level\":\"ERROR\",\"message\":\"[08-03-2024 16:10:51] | Request failed |.....",
        "2": "{\"environment\":\"development\",\"level\":\"ERROR\",\"message\":\"[08-03-2024 16:13:14] | Request failed |.....",
        "3": "{\"environment\":\"development\",\"level\":\"ERROR\",\"message\":\"[08-03-2024 16:17:10] | Request failed |....."
    }
}

Not the best solution, but sufficient for me.

热风软妹 2025-02-03 04:20:44

如果目标只是对事物的开发人员端的可读性,而实际上不需要字符串数据中的新线a>。在JSON字符串中,无论 \ n 在任何地方,都可以使用可能的可能呈现软线破裂,但是我使用的任何工具实际上都没有。

请注意, json5 支持通过在多行上放置 \ 在多行上跨越跨越字符串的编写。下一行继续的线路的末端。实际上,这实际上并没有将这些位置的newline字符放入JSON字符串中,尽管您可以手动添加 \ n 来获取它。


否则,如果您实际上希望字符串数据包含一个newline,其中您在JSON字符串中插入一个未塑造的新线字符,则答案是“不,您不能*”。

Douglas Crockford(JSON的创建者) “ 32个控制代码”。

如果您想要更精确的东西, rfc document> rfc document(8259) a>:

所有Unicode字符都可以放置在报价标记中,除了必须逃脱的字符:引号标记,反向固体和控制字符(u+0000至u+001f)。

因此,没有 uteapate,字面的运输返回或线馈送。您只能通过使用逃生序列( \ n )将Newline(线馈)放入JSON字符串中,大多数工具不会将其作为视觉线分隔符(尽管这并不是说他们可以'可以' t-只是他们通常不会)。


* 技术上 ,在Unicode中定义了一个newline字符,它被允许在JSON字符串中为无示例的文字: u+2028 (另请参见什么Unicode字符2028(LS /线分离器)是否用于?但这是一个相对晦涩的编码点,您的里程会因您的开发人员工具是否将其作为线路分离器或其他东西(例如)呈现。我刚刚使用VS代码进行了测试,并发出了有关“不寻常的线分隔符”的警告,并将其呈现为``。另外,不仅是开发工具,而且由于这是实际内容,因此系统的其余部分都会看到(例如,将文本传递给用户)。您的里程也会在那里有所不同。

也就是说,作为解决方法,这并不是真正的实用性。

有趣的事实:u+2028据说在JSON字符串中有效,但在JavaScript中无效,WebPack(例如WebPack)的一些JavaScript Bundler工具必须逃脱以“将JSON放入JS”(在这里)。

If you aim is just readability for the developer side of things and you don't actually want newlines in the string data, then yes, check if your tooling supports soft wrapping. It's also possible for tooling to render soft linebreaks wherever a \n is in a JSON string, but none of the tools I use actually do that.

Note that JSON5 supports spanning the writing of a string across multiple lines by placing a \ at the end of a line that continues on the next line. This does not actually put a newline character at those places into the JSON string, though you can manually add a \n to get that.


Otherwise, if you actually want the string data to contain a newline where you insert an unescaped newline character in the JSON string, the answer is "no, you can't*".

By Douglas Crockford (the creator of JSON)'s JSON specification, a string cannot contain any of "the 32 control codes".

If you want something more precise, the RFC document (8259) for JSON says:

All Unicode characters may be placed within the quotation marks, except for the characters that MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

So no unescaped, literal carriage returns or line feeds. You can only put a newline (line feed) in JSON strings by using escape sequences (\n), which most tooling will not render as a visual line separator (though that's not to say that they couldn't- just that they usually don't).


* Technically, there is a newline character defined in Unicode that is allowed as an unescaped literal inside a JSON string: U+2028 (see also What is unicode character 2028 (LS / Line Separator) used for? TL;DR "unambiguous newline character"). But it's a relatively obscure codepoint, and your mileage will vary on whether your developer tools will render it as a line separator, or as something else (like �). I just tested with VS Code, and it issues a warning about "unusual line separators", and renders it as �. Also, not just the dev tooling, but since this is actual content, it will be what the rest of the system sees (Ex. machinery that renders the text to a user). Your mileage will vary there as well.

That is to say that this is not really practical as a workaround.

Fun fact: U+2028 is supposedly valid in JSON strings, but not in JavaScript, and some JavaScript bundler tools like Webpack have to do escaping to "put JSON in JS" (here).

一枫情书 2025-02-03 04:20:44

\ n \ r \ n 为我工作!

\ n 用于单线断路和 \ n \ r \ n 双线路休息

\n\r\n worked for me !!

\n for single line break and \n\r\n for double line break

陈甜 2025-02-03 04:20:44

我在这里看到许多答案,在大多数情况下可能无法使用,但如果您想在JSON文件中输出所写内容,则可能是最简单的解决方案(例如:对于语言翻译,您只想拥有一个超过1个键在客户端上输出的行)可以只是添加您选择的一些特殊字符 ps:json文件允许喜欢 \\ 在新行之前,然后使用一些JS来解析文本...喜欢:

示例:

file(text.json)

{“ text”:“一些json文本。

import text from 'text.json'
{text.split('\\')
.map(line => {
return (
   <div>
     {line}
     <br />
   </div>
     );
})}}

I see many answers here that may not works in most cases but may be the easiest solution if let's say you wanna output what you wrote down inside a JSON file (for example: for language translations where you wanna have just one key with more than 1 line outputted on the client) can be just adding some special characters of your choice PS: allowed by the JSON files like \\ before the new line and use some JS to parse the text ... like:

Example:

File (text.json)

{"text": "some JSON text. \\ Next line of JSON text"}

import text from 'text.json'
{text.split('\\')
.map(line => {
return (
   <div>
     {line}
     <br />
   </div>
     );
})}}
盛夏尉蓝 2025-02-03 04:20:44

您可以在单个线路中添加‍‍ \ n,而\ n \ r \ n则可以在这样的JSON字段值中进行双层断路。 (在数据库中)

{
    "app": {
       "result": "You have saved \n life",
     }
}

当您渲染此JSON对象时,添加白空间:pre-line; css属性到您的&lt; div&gt; &lt; span&gt; < /代码>标签。这将在\ n上打破您的文字。

<span style={{whiteSpace: 'pre-line'}}>{data?.yourjsonobject.app.result}</span>

You can add ‍‍\n for single line break and \n\r\n for double line break in your JSON Field values like this. (in database)

{
    "app": {
       "result": "You have saved \n life",
     }
}

When you render this JSON object add white-space: pre-line; CSS property to your <div> or <span> tag. This will break your text at \n.

<span style={{whiteSpace: 'pre-line'}}>{data?.yourjsonobject.app.result}</span>
笑脸一如从前 2025-02-03 04:20:44

如果仅在您的编辑器中进行演示,则可以使用```''或'

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

示例:

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

将放入控制台:
第一线第二行将

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

放置在控制台中:
第一行
第二行

希望这能回答您的问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文