2013-02-21 87 views
0

我收到以下错误时:错误解析JSON字符串

uncaught exception: Invalid 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") 
      } 
     }); 

任何想法可能是错的?

+0

的JSON是无效的,看http://jsonlint.com/这可以帮助您。 – 2013-02-21 10:37:53

回答

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" 
    } 
} 
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" 
    }" 
} 
0

数据有问题EM

{"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...这部分有错误u需要逃避作为\"nick或本shud是数据

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

第二个例子也是无效的JSON。字符串总是用双引号表示。 – 2013-02-21 10:25:52

+0

感谢您的标记,但我已经在声明中指定了要逃避引号。 – Sandeep 2013-02-22 05:14:50