【问题标题】:Returning json without " after migrating to python 2.7迁移到 python 2.7 后返回不带 " 的 json
【发布时间】:2013-10-09 14:04:39
【问题描述】:

我刚刚从 python 2.5 迁移到 python 2.7 并用内置的 json 替换了 simplejson。但现在我收到一个 json 错误“JSON.parse:预期的属性名称或 '}'。”

返回的json是:

{
  "stat"    : "ok",
  "code"    : "200",
  "message" : "Retrieved departments from account.",
  "result"  : [{"id": "5486563022602240", "name": "The     
  New Establishment"}, {"id": "6049512976023552", 
  "name": "Ye Olde Joynt"}]
}

似乎我可以在前端 (JSON.parse: expected property name or '}') 中进行一些字符串替换,但它不应该是我的服务,它返回正确格式的数据吗?我目前在 python 中生成数据是这样的:

def department_getlist(self):
    self.message = 'Retrieved departments from account.'
    results = []
    for d in self.account.departments:
      results.append({
        'id': str(d.key().id()),
        'name': d.name
      })
    self.result = json.dumps(results)

如何在 python 中生成数据,以便以正确的格式返回(如果这样做的话)?

谢谢

托马斯

【问题讨论】:

  • 你确定这是生成 json 的完整代码吗?我在顶部返回的 json 中没有看到任何 idname 键。
  • @Michael0x2a 你是对的。我更新了返回的 json 以显示正确的版本。另一个 json 来自应用程序的另一部分

标签: python json python-2.7


【解决方案1】:

我怀疑在某个地方,你打电话给json.dumps 两次而不是一次。

在您的 department_getlist 函数中,您执行 self.result = json.dumps(results)。我猜在别的地方,你做的事情的效果是:

message = {
  "stat"    : "ok",
  "code"    : "200",
  "message" : "Retrieved departments from account.",
  "result"  : self.results
}

output = json.dumps(message)

如果是这样,您将在 self.results 变量上调用 json.dumps 两次,并在第二次传递时转义引号。当您的前端 Javascript 解析并显示 JSON 时,它可能会将转义字符串显示为",而不是\"

尝试将department_getlist 函数中的行更改为self.result = results,看看是否能解决问题。

【讨论】:

  • @MichaelOx2a 感谢您的建议。它让我做一个回溯来跟踪代码的执行。解决方案是在我的 json-template 中使用 {% autoescape off %}: { "stat" : "{{ status }}", "code" : "{{ code }}", "message" : "{{ message }}"{% if result %}, "result" : {% autoescape off %}{{ result }}{% endautoescape %}{% endif %} }
  • @ThomasD - 啊,我明白了。我想我当时完全错了:)。您应该考虑将您的解决方案写成一个新的答案,并为将来可能遇到同样问题的其他人的利益而接受它。
  • 您的答案可能并不完全正确,但您让我走上了正确的道路 :-) 我添加了一个简短的描述作为答案。再次感谢
【解决方案2】:

感谢 Michael0x2a 的评论,我回溯了我的代码并找到了解决方案 采用 {% autoescape off %} 在我的 json 模板中:

{
  "stat"    : "{{ status }}",
  "code"    : "{{ code }}",
  "message" : "{{ message }}"{% if result %},
  "result"  : {% autoescape off %}{{ result }}{% endautoescape %}{% endif %}
}

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 2016-06-17
    • 2012-11-01
    • 1970-01-01
    • 2015-09-21
    • 2022-11-04
    • 2018-10-17
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多