2012-05-23 90 views
1

我有一個字符串,我想解碼成json。該字符串最初是base64。當我嘗試解碼成傑森時,我得到下面的錯誤。Node.js不能解析來自base64解碼的JSON字符串

var query_string = new Buffer(bid, 'base64').toString('ascii'); 
    console.log(query_string); 
    var q = JSON.parse(query_string); 


{'avid': '[email protected]', 'crid': '20767073515', 'mabid': {'node': None, 'hod': '13', 'cid': '36', 'industry': None, 'ex': '1', 'vid1': '29', 'dow': '3'}, 'prid': {'hod': '13', 'woy': '18', 'cid': '36', 'dow': '3', 'ssp': 'adx', 'st': None, 'bt': 'firefox', 'cty': 'tokyo', 'ex': '1', 'vid2': '222', 'dt': '1', 'os': 'mac', 'vid1': '29'}, 'agid': '4547917795', 'cookieid': 'retageting:cookie', 'did': 'yahoo.com', 'validation': True} 

SyntaxError: Unexpected token ' at Object.parse (native) at /home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/app.js:115:16 at callbacks (/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/node_modules/express/lib/router/index.js:272:11) at param (/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/node_modules/express/lib/router/index.js:246:11) at pass (/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/node_modules/express/lib/router/index.js:253:5) at Router._dispatch (/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/node_modules/express/lib/router/index.js:280:4) at Object.handle (/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/node_modules/express/lib/router/index.js:45:10) at next (/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/node_modules/express/node_modules/connect/lib/http.js:204:15) at Object.methodOverride [as handle] (/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:35:5) at next (/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbNodejsServer/node_modules/express/node_modules/connect/lib/http.js:204:15)

回答

4

JSON格式要求雙引號,不單引號

另外:

  • 應該是:
  • 應該是小寫:真正

QUERY_STRING應該看起來像下面這樣:

{"avid": "[email protected]", "crid": "20767073515", "mabid": {"node": null, "hod": "13", "cid": "36", "industry": null, "ex": "1", "vid1": "29", "dow": "3"}, "prid": {"hod": "13", "woy": "18", "cid": "36", "dow": "3", "ssp": "adx", "st": null, "bt": "firefox", "cty": "tokyo", "ex": "1", "vid2": "222", "dt": "1", "os": "mac", "vid1": "29"}, "agid": "4547917795", "cookieid": "retageting:cookie", "did": "yahoo.com", "validation": true} 

我想這是一個Python字典,你應該使用一個圖書館正確序列化的Python字典JSON,或者如果您正在使用Python 2.6+,簡單地做:

import json 
json_string = json.dumps({'test': 'test'}) 

文檔:http://docs.python.org/library/json.html

+0

嗯......呃......這個字符串起源於一個python d ictionary,轉換爲jason然後base64。 Python可以解碼,但猜測節點不能 – Tampa

+0

更新回答上面 – BFil

+0

Ahhhhhhh ......笨拙的我....我最初使用龍捲風......它都在同一個家庭。我使用import ast來將字符串解碼爲一個python dic。 – Tampa

1

JSON需要圍繞鍵和(字符串)值使用雙引號,而不是單引號。

另外:

  1. None是不是合法的值 - JSON的方式來編碼空的關鍵是"mykey": null
  2. TrueFalse必須是小寫的

正式文法JSON位於首頁http://www.json.org/