【问题标题】:Parsing Json data sent by android clinet using "post" request in django view在django视图中使用“post”请求解析android clinet发送的Json数据
【发布时间】:2014-03-18 06:00:45
【问题描述】:

我正在尝试循环我的 android 客户端发送的 json 数据。我使用了下面的代码,但它不适合我。我正在做的任何可能的错误...??????

def api_json(request):
    try:
        x101=json.loads(request.body)
        print x101
        for data in x101:
            print data+"xp"
            asset_code=data['asset_code']
            credential=data['credential']
            d1=data['d1']
            d2=data['d2']
            d3=data['d3']
            angle=data['angle']
            status=data['status']
            operator=data['operator']
            location=data['location']
            print asset_code,credential,d1,d2,d3,angle,status,operator,location
            v=Verification(asset_code=asset_code,
                          scan_time=datetime.datetime.now(),
                          credential=credential,
                          d1=d1,
                          d2=d2,
                          d3=d3,
                          angle=angle,
                          status=status,
                          operator=operator,
                          location=location,
                          image='')
            v.save()
    except:
        print 'nope'
    return HttpResponse('success')

错误跟踪:

TypeError: string indices must be integers

【问题讨论】:

  • 打印的是“不”吗?我会删除巨大的 try/except 并找出错误来自哪里。
  • 是的,它的印刷不正确
  • “请求”从何而来?如果是requests库,可以使用r = request.json来加载json,而不是body。
  • 但它对我不起作用 不是问题描述。它怎么不适合你?如果除了处理(总是一个坏主意)之外,您移除毯子会发生什么?
  • 请删除 try-except 并使用错误堆栈跟踪更新问题。

标签: python django


【解决方案1】:

假设您的 JSON 解码为字典,for data in x101 会遍历该字典的 键。所以data['d1'] 会给出你看到的 TypeError,“字符串索引必须是整数”。

由于您完全没有提供有关数据结构实际外观的详细信息,我们只能猜测,但您可能希望使用for data in x101.values() 遍历字典的值。

在任何情况下,您绝对应该删除除了打印“nope”之外什么都不做的 try/except。出现错误是有原因的,将它们静音只会阻止您正确调试,正如我们在此处看到的那样。

编辑

x101 只是一个字典。您说经常会有多个字典,但它不可能像那样工作:拥有多个字典的唯一方法是将它们放在一个列表中(即 JSON 数组)。如果是这样,他们将必须始终在一个列表中,即使只有一个。所以你的结构应该是:

[
  {
    "angle": "10", 
    "asset_code": "XPS1020", 
    "credential": "wqw2323ds2", 
    "d1": "1", 
    "d2": "2", 
    "d3": "3", 
    "location": "Bangalore", 
    "operator": "pradeep", 
    "status": "1"
  }
]

然后您的代码将按原样运行,无论是单个还是多个。

【讨论】:

  • 是的 Danial 我删除了 try/except 并且我得到了与您指出的相同的错误“TypeError:字符串索引必须是整数”
  • 并在打印 x101 时进行调试,我得到类似这样的内容 {u'status': u'1', u'credential': u'wqw2323ds2', u'angle': u' 10', u'asset_code': u'XPS1020', u'location': u'Bangalore', u'operator': u'pradeep', u'd2': u'2', u'd3': u' 3', u'd1': u'1'}
  • 好吧,那么 x101 只是一个单一的字典,你根本不想遍历它。只需直接访问它 - 即删除 for 语句,并在任何地方使用 x101 而不是 data。
  • 但预计很多时候会有多个以逗号(,)分隔的字典,然后如何在模型中处理和更新它们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
相关资源
最近更新 更多