2

Given this Json

{
"myclass": {
    "studentname": "myname",
    "description": "Student has three more credits to complete\n
    he is taking maths\ n
    biology this semester "
 }
}

I get a Json parser exception for 'description' in jsonlint. Changing the description to accept an array is not an option for me.

Is there any way to define multiline in Json?

Anuram
  • 63
  • 1
  • 1
  • 6

1 Answers1

3

\n is the only way. JSON isn't programming language and you can't tell it to concatenate string. It depends on context too.

This will work

{
    "myclass": {
        "studentname": "myname",
        "description": "Student has three more credits to complete\nhe is taking maths\nbiology this semester"
     }
}

This will not work

{
    "myclass": {
        "studentname": "myname",
        "description": "Student has three more credits to complete\n
                        he is taking maths\n
                        biology this semester"
     }
}
Oen44
  • 3,156
  • 1
  • 22
  • 31
  • JSON editor throws an error as well. You cannot have literal line breaks in string literals. – Felix Kling Dec 10 '18 at 23:21
  • Actually not, it's just about saving, open fresh and paste that JSON there. No errors. – Oen44 Dec 10 '18 at 23:22
  • When I paste it the right hand side does not update, so I have to assume that it doesn't work, even if it doesn't explicitly show an error. – Felix Kling Dec 10 '18 at 23:23
  • Press button with right arrow. It's not auto updating. – Oen44 Dec 10 '18 at 23:24
  • 1
    I see... but it doesn't matter what the editor is doing. The error when loading clearly shows that `JSON.parse` doesn't like it, so it cannot be valid. [The JSON spec](https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) also says *"Whitespace is not allowed within any token, except that space is allowed in strings."* – Felix Kling Dec 10 '18 at 23:27
  • Well, lets consider 2nd example as not working then. – Oen44 Dec 10 '18 at 23:28
  • I have a very long string and writing it in a single line with \n makes it really clumsy. Is there any other way to do this? – Anuram Dec 10 '18 at 23:31
  • 1
    @Anuram How about doing it your way, then changing every breakline to `\n` and passing that string as JSON value? – Oen44 Dec 10 '18 at 23:39