JSON意外令牌

时间:2017-03-21 19:03:49

标签: javascript json

我有以下JSON字符串

    {"rules": {
  "firstName": {
    "required": true,
    "range": "[2,50]"
  },
  "lastName": {
    "required": true,
    "range": "[2,50]"
  },
  "email": {
    "required": true,
    "email": true
  },
  "email2": {
    "equalTo": "email",
    "required": true
  },
  "password": {
    "required": true,
    "range": "[5,25]"
  },
  "password2": {
    "equalTo": "password",
    "required": true
  },
  "termsConfidentiality": {
    "required": true
  }
},
"messages": {

    "termsConfidentiality": {
        "required": "You must accept the Terms of Use and Privacy Policy in order to register."
    },
    "termsConfidentiality": {
        "required": "You must accept the Terms of Use and Privacy Policy in order to register."
    }
},
"errorPlacement": function(error, element) {
    if (element.attr('name') == 'termsConfidentiality') {
                        error.appendTo($('#terms'));
    }
}
}

我保留在一个名为rules的变量中。当我JSON.parse(rules)时,我收到以下错误

39 Uncaught SyntaxError: Unexpected token u in JSON

在我添加errorPlacement之前,一切正常。意外的令牌是单词'u'中的字母'function'。格式化它的正确方法是什么,以便我可以在之后解析它?

2 个答案:

答案 0 :(得分:2)

正如@epascarello所说,“一个函数在JSON中无效”。不要混淆JSON和Javascript,即使它们共享一个名字,它们也是相互独立的。您不能在JSON中使用函数,因为它不是一种语言,而是一种数据格式。您可以将函数封装为字符串,然后使用eval函数运行它,虽然我不建议这样做,这是一个非常脏的黑客,并且非常不安全。

答案 1 :(得分:0)

如前所述,不要混淆json和javascript。 同样在邮件中,您有重复的密钥:

"messages": {

    "termsConfidentiality": {
        "required": "You must accept the Terms of Use and Privacy Policy in order to register."
    },
    "termsConfidentiality": {
        "required": "You must accept the Terms of Use and Privacy Policy in order to register."
    }
}

有效的JSON ::

  {
        "rules": {
            "firstName": {
                "required": true,
                "range": "[2,50]"
            },
            "lastName": {
                "required": true,
                "range": "[2,50]"
            },
            "email": {
                "required": true,
                "email": true
            },
            "email2": {
                "equalTo": "email",
                "required": true
            },
            "password": {
                "required": true,
                "range": "[5,25]"
            },
            "password2": {
                "equalTo": "password",
                "required": true
            },
            "termsConfidentiality": {
                "required": true
            }
        },
        "messages": {
            "termsConfidentiality": {
                "required": "You must accept the Terms of Use and Privacy Policy in order to register."
            }
        }
    }