python for循环不返回多个字典

时间:2014-10-22 19:34:22

标签: python django

我希望来自xml_parser视图的json响应。我只得到一个dict而不是多个dict ..似乎我的for循环逻辑错了..你能纠正我吗??

def xml_parser(request):
    for child in root.findall('GetAll'):
        for geoloc in child.iter('loc'):
            geoinfo = geoloc.attrib
            pprint.pprint(geoinfo)
    jsoninfo = json.dumps(geoinfo, ensure_ascii=False)
    return HttpResponse(jsoninfo, content_type='application/json')

好的,现在pprint显示,这是我想要的确切输出

{'lat': '36.15900011', 'lon': '-115.17205183'}
{'lat': '36.15899561', 'lon': '-115.17276155'}

但网址http://127.0.0.1:8000/parser显示{"lat": "36.15899561", "lon": "-115.17276155"}我可能知道原因吗?

2 个答案:

答案 0 :(得分:2)

jsoninfo的赋值发生在for循环之外,但geoinfo的赋值发生在它内部。您需要将所有geoloc.attrib值聚合到一个列表中,并在最后将其转换为json:

def xml_parser(request):
    infos = []

    for child in root.findall('GetAll'):
        for geoloc in child.iter('loc'):
            infos.append(geoloc.attrib)

    jsoninfo = json.dumps(infos, ensure_ascii=False)
    return HttpResponse(jsoninfo, content_type='application/json')

这假设您实际上想要输出一个JSON对象作为您的响应,而不是两个由换行符分隔的独立对象的编码。

答案 1 :(得分:0)

每次循环时都会覆盖geoinfo。您没有存储所有结果。考虑创建一个空列表,附加到它,然后将其作为响应发送回来

相关问题