【问题标题】:No JSON object could be decoded - RPC POST call无法解码 JSON 对象 - RPC POST 调用
【发布时间】:2012-04-15 17:36:02
【问题描述】:
var body = JSON.stringify(params);

// Create an XMLHttpRequest 'POST' request w/ an optional callback handler
req.open('POST', '/rpc', async);

req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", body.length);
req.setRequestHeader("Connection", "close");

if (async) {
  req.onreadystatechange = function() {
    if(req.readyState == 4 && req.status == 200) {
      var response = null;
      try {
        response = JSON.parse(req.responseText);
      } catch (e) {
        response = req.responseText;
      }
      callback(response);
    }
  };
}

// Make the actual request
req.send(body);

----在服务器端----

class RPCHandler(BaseHandler):        
'''@user_required'''
def post(self):
    RPCmethods = ("UpdateScenario", "DeleteScenario")
    logging.info(u'body ' + self.request.body)
    args = simplejson.loads(self.request.body)

---- 在服务器日志上得到以下错误 正文 %5B%22UpdateScenario%22%2C%22c%22%2C%224.5%22%2C%2230frm%22%2C%22Refinance%22%2C%22100000%22%2C%22740%22%2C%2294538%22% 2C%2250000%22%2C%22owner%22%2C%22sfr%22%2C%22Fremont%22%2C%22CA%22%5D=

无法解码 JSON 对象:第 1 行第 0 列(字符 0): 回溯(最近一次通话最后): 调用中的文件“/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py”,第 703 行 handler.post(*groups) 文件“/base/data/home/apps/s~mortgageratealert-staging/1.357912751535215625/main.py”,第 418 行,在帖子中 args = json.loads(self.request.body) 加载中的文件“/base/python_runtime/python_lib/versions/1/simplejson/init.py”,第 388 行 返回 _default_decoder.decode(s) 解码中的文件“/base/python_runtime/python_lib/versions/1/simplejson/decoder.py”,第 402 行 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 文件“/base/python_runtime/python_lib/versions/1/simplejson/decoder.py”,第 420 行,在 raw_decode raise JSONDecodeError("没有 JSON 对象可以被解码", s, idx) JSONDecodeError:无法解码 JSON 对象:第 1 行第 0 列 (char 0)

--- firebug 显示如下 ---

参数 application/x-www-form-urlencoded ["UpdateScenario","c","4....
资源 ["UpdateScenario","c","4.5","30frm","Refinance","100000","740","94538","50000","owner","sfr","Fremont","加州"]

根据萤火虫报告和日志显示 self.request.body 符合预期。但是 simplejson 加载不喜欢它。

请帮忙!

【问题讨论】:

    标签: google-app-engine json-rpc


    【解决方案1】:

    两个选项:

    看来需要对self.request.body的内容进行转义。

    导入 urllib 并将示例中的最后一行代码更改为:

    args = simplejson.loads(urllib.unquote(self.request.body))

    或者您可以尝试其他选项:您在 POST 正文中发送完整的 json 字符串。您可能不需要在 javascript 中包含以下行:

    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    取出来,看看是否还需要使用上面的urllib.unquote解决方案。

    【讨论】:

    • 不客气。请点击左侧“0”附近的“复选标记”,将正确答案标记为正确答案。 :}
    【解决方案2】:

    您不发送 JSON 内容。您必须添加此标头: contentType: 'application/json'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2022-07-11
      相关资源
      最近更新 更多