English 中文(简体)
Node.js 无法从 base64 解码中解析 JSON 字符串
原标题:Node.js cant parse a JSON string from base64 decode

我有一个字符串,我想解码成json。字符串最初是基底64。我试着解码成Jason,我得到了以下错误。

  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)

最佳回答

JSON格式要求“强”双引号 "/强 ",而不是 " 强 " 单引号 "/强 " 。

此外:

  • None should be: null
  • True should be lowercase: true

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' rel=“nofollow'>http://docs.python.org/library/json.html

问题回答

JSON需要在键和(字符串)值周围双引号,而不是单引号。

此外:

  1. None is not a legal value - the JSON way to encode an empty key is "mykey": null
  2. True and False must be in lower case

JSON的正式语法在首页