0

我收到以下错误:

未捕获的异常:无效的 JSON:{"id":1,"channel":"V125954","text":"{"nick":"Du","visit":"1","text":"hello" ,"_ref":"Du","_cur":"Du","_ip":"Du","_browser":"Du","_os":"Du","_td":"12:29" }"}

尝试使用以下函数解析时:

  var parseJSON = function(data) {
    if (!data || !isString(data)) {
      return null;
    }

    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = trim(data);

    // Attempt to parse using the native JSON parser first
    if (window.JSON && window.JSON.parse) {
      try {
        return window.JSON.parse( data );
      } catch(e) {
        throw "Invalid JSON: " + data;
        console.log(e);
      }
    }

    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if (validChars.test(data.replace(validEscape, "@").replace( validTokens, "]").replace( validBraces, "")) ) {
      return (new Function("return " + data))();
    }

    throw "Invalid JSON: " + data;
  };

通过nodejs发送数据是这样的:

        var options = {
          uri: 'http://localhost/pub?id=' + req.params.channel,
          method: 'POST',
          json: {
            "nick": "Du",
            "visit": "1",
            "text": "hej",
            "_ref": "Du",
            "_cur": "Du",
            "_ip": "Du",
            "_browser": "Du",
            "_os": "Du",
            "_td": "12:29",                                                                                                                                                             
          }
        };

        request_helper(options, function (error, response, body) {
          if (!error && response.statusCode == 200) {
            console.log("ok") 
          }
        }); 

有什么想法可能是错的吗?

4

3 回答 3

0

您的 json 无效。

使用 http://jsonlint.com/来验证您的 json 文件。

更正的json

{
    "id": 1,
    "channel": "V125954",
    "text": {
        "nick": "Du",
        "visit": "1",
        "text": "hello",
        "_ref": "Du",
        "_cur": "Du",
        "_ip": "Du",
        "_browser": "Du",
        "_os": "Du",
        "_td": "12: 29"
    }
}
于 2013-02-21T10:18:06.000 回答
0

您的 JSON 字符串无效,这就是您收到错误的原因。尝试类似:

{
    "id": 1,
    "channel": "V125954",
    "text": {
        "nick": "Du",
        "visit": "1",
        "text": "hello",
        "_ref": "Du",
        "_cur": "Du",
        "_ip": "Du",
        "_browser": "Du",
        "_os": "Du",
        "_td": "12: 29"
    }
}

您可以在http://jsonlint.org/验证您的 JSON 字符串

JSON 中嵌套结构的正确语法是:

{
   "obj": {
        "foo": "bar"
    }
}

不是

{
   "obj": "{
        "foo": "bar"
    }"
}
于 2013-02-21T10:18:18.277 回答
0

数据有问题

{"id":1,"channel":"V125954","text":"{"nick":"Du","visit":"1","text":"hello","_ref":"Du","_cur":"Du","_ip":"Du","_browser":"Du","_os":"Du","_td":"12:29"}"}

"text": "{"nick":"Du...这部分有错误你需要转义,\"nick否则这应该是数据

{"id":1,"channel":"V125954","text":'{"nick":"Du","visit":"1","text":"hello","_ref":"Du","_cur":"Du","_ip":"Du","_browser":"Du","_os":"Du","_td":"12:29"}'};
于 2013-02-21T10:20:21.737 回答