31

IMPORTANT: I am not asking about rendering strings as multiline.

I am talking about splitting a long string in a JSON into multiple lines in my source code when this string should logically be on a single line.

In short: I want source line breaking rules similar to HTML.

{
    "id": 550,
    "text": "this is long text "
            "very-very-very long text "
            "longer than you can imagine."
}

This text should be rendered as:

this is long text very-very-very long text longer than you can imagine.

The JSON is being referenced in JavaScript.

This is not a duplicate of Multiline strings in JSON because this question strongly refers to JavaScript and that question has no clear accepted answer.

Paul
  • 25,812
  • 38
  • 124
  • 247
  • Possible duplicate of [Multiline strings in JSON](https://stackoverflow.com/questions/2392766/multiline-strings-in-json) – Francisco Puga Feb 11 '18 at 20:02
  • 3
    @Francisco Puga: only to 70% – Paul Feb 11 '18 at 20:07
  • 1
    This is not a duplicate because that one is about \n inside string while this one is about how the same content is represented differently (more readable) in the JSON source. – user202729 Aug 29 '18 at 08:13

4 Answers4

12

You can use multiple lines string representation in JavaScript:

JSON.parse('{"a" : "a\
asd"}')

Tried in console. It works.

Volker E.
  • 5,911
  • 11
  • 47
  • 64
Alex
  • 11,115
  • 12
  • 51
  • 64
3

Use an array:

{
    "id": 550,
    "text": ["this is long text ",
            "very-very-very long text ",
            "longer than you can imagine."]
}

Assuming that this goes in this.messages, use in code

this.messages.text.join();
horiatu
  • 356
  • 2
  • 10
0

According to JSONLint.com, the following multiline JSON is valid. So in short, yes, you can hit enter and break it into different lines.

{
    "a": 10,
    "b": 12,
    "c": 19
}

EDIT: I think I misread your question. I don't think you're able to break between a string like below. That does not work.

{
    "a": "abcde
    fg",
    "b": 12,
    "c": 19
}
mjkaufer
  • 4,047
  • 5
  • 27
  • 55
  • Can you explain the context? What language are you writing in, why do you need a line break, etc.? – mjkaufer Jan 12 '14 at 16:31
  • You may use an array of strings as in "a" : ["abcde", "fg"], Then in your js code use either join() (for a long line of text as "abcdefg") or join("\n") for a text representation of two lines. – horiatu Dec 03 '21 at 06:15
-2

You can't do it, you need to write the value in one line, if you want write in the next row, you need to put \n in your code

  • 2
    The question says clearly that it should be rendered as one row – lfk Mar 15 '18 at 23:14
  • He explicitly said that he is “not asking about *rendering* strings as multiline.” Perhaps you could give an example of how to work around this problem using JavaScript? Sorta like [Pinal’s answer](https://stackoverflow.com/a/21077197/6845130). – Danny May 02 '21 at 06:51