2014-03-26 37 views
0

在以下JSON文檔中,如何轉義換行符?目前,該文件未通過驗證。JSON文檔轉義字符

{ 
    "questionId" : 1, 
    "text" : "Given the following code, what gets printed?", 
    "questype" : "RADIO_BUTTON", 
    "issourcecode" : true, 
    "sourcecode" : "def patternMatcher(list: List[Int]) = list match { \\n\\n 
         case Nil => \"The List is empty\" \n 
         case x :: Nil => s\"The List contained $x\" \n 
         case x :: xss => s\"The List contained $x and $xss\" \n 
         case _ => \"None of the above\" \n 
        } 
        patternMatcher(List(1,2,3,4)) -- What gets printed here?", 
    "examId" : 1000, 
    "answers" : [ 
     { 
      "id" : 1, 
      "text" : "The List is empty", 
      "isCorrectAnswer" : false 
     }, 
     { 
      "id" : 2, 
      "text" : "The List contained 1", 
      "isCorrectAnswer" : false 
     }, 
     { 
      "id" : 3, 
      "text" : "The List contained 1 and List(2,3,4)", 
      "isCorrectAnswer" : true 
     }, 
     { 
      "id" : 4, 
      "text" : "None of the above", 
      "isCorrectAnswer" : false 
     } 
    ] 
} 

它在第6行發生錯誤,換行符所在的位置!

我後來改變了JSON以下:

{ 
    "questionId" : 1, 
    "text" : "Given the following code, what gets printed?", 
    "questype" : "RADIO_BUTTON", 
    "issourcecode" : true, 
    "sourcecode" : "def patternMatcher(list: List[Int]) = list match {\\n 
         case Nil => \"The List is empty\" \\n 
         case x :: Nil => s\"The List contained $x\" \\n 
         case x :: xss => s\"The List contained $x and $xss\" \\n 
         case _ => \"None of the above\" \\n 
        } 
        patternMatcher(List(1,2,3,4)) -- What gets printed here?", 
    "examId" : 1000, 
    "answers" : [ 
     { 
      "id" : 1, 
      "text" : "The List is empty", 
      "isCorrectAnswer" : false 
     }, 
     { 
      "id" : 2, 
      "text" : "The List contained 1", 
      "isCorrectAnswer" : false 
     }, 
     { 
      "id" : 3, 
      "text" : "The List contained 1 and List(2,3,4)", 
      "isCorrectAnswer" : true 
     }, 
     { 
      "id" : 4, 
      "text" : "None of the above", 
      "isCorrectAnswer" : false 
     } 
    ] 
} 

我用下面的網站來驗證我的JSON,它總是失敗,出現以下錯誤:

http://www.freeformatter.com/json-validator.html

The JSON input is NOT valid in JavaScript, unterminated string literal (At line #6), (At position #73) 
+1

這可能有所幫助http://stackoverflow.com/a/4253415/1324816 – user6123723

回答

0

好!只要我改變以反映以下,它的工作:

"sourcecode" : "def patternMatcher(list: List[Int]) = list match {\\n case Nil => \"The List is empty\" \\n case x :: Nil => s\"The List contained $x\" \\n case x :: xss => s\"The List contained $x and $xss\" \\n case _ => \"None of the above\" \\n}patternMatcher(List(1,2,3,4)) -- What gets printed here?" 

我必須在一行中。奇怪!