JSON文档转义字符

时间:2014-03-26 06:18:39

标签: 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 个答案:

答案 0 :(得分: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?"

我必须把它放在一行中。奇怪!