【问题标题】:Parsing JSON-file with Python in Django在 Django 中使用 Python 解析 JSON 文件
【发布时间】:2016-08-18 11:33:51
【问题描述】:

我有查询我在哪里获取 JSON 文件并希望在 HTML 中显示表中的数据。我现在收到错误:TypeError: string indices must be integers in line: 'status': item['status'],.是外括号的问题,因为它们在 json 中丢失还是什么?

views.py 代码

json_obj = urllib2.urlopen(url)
data = json.load(json_obj)
results = []
for item in data:
    results.append({
        'status': item['status'],
        'device': item['device'],
       })
return render(request, 'index/index.html', {'objects_list': results})

JSON 文件:

{
  “version": “3.62”,
  "treesize": 2,
  "": [
    {
      “status”: “up”,
      "device": “someDeviceName1”,
    }
    {
      “status”: “up”,
      "device": “someDeviceName2”,
    }]
}

【问题讨论】:

  • data 是包含三个元素的字典:"version""treesize"""
  • json.load(json) 毫无意义。您的输入是否真的存储在变量json 中?
  • DisplayName 所说的。 json = urllib2.urlopen(url) 将名称 json 绑定到 URL 句柄,因此它不再引用 json 模块。
  • @DisplayName 真的没有。我现在将其编辑为问题。

标签: python json django django-views


【解决方案1】:

我不知道你是否不小心把 JSON 内容复制错了,但你应该做的是:

>>> for item in data[""]:
...     results.append({ ...

【讨论】:

  • 是的,这就是我所缺少的。也许我只是感到困惑,该数组没有名称。
  • 在响应中添加 read() 给我一个错误:AttributeError: 'str' object has no attribute 'read'
  • 当我将 data[""] 添加到 views.py 中的原始代码时,将此添加到正确答案中。
  • 或者,使用列表理解:)
猜你喜欢
  • 2023-04-02
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多