Reputation:
I want json response from xml_parser
view.I am getting only one dict instead of multiple dict .. seems my for loop logic is wrong .. can you correct that for me..?
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')
Okay now pprint shows and this is the exact output i want
{'lat': '36.15900011', 'lon': '-115.17205183'}
{'lat': '36.15899561', 'lon': '-115.17276155'}
but the url http://127.0.0.1:8000/parser
shows {"lat": "36.15899561", "lon": "-115.17276155"}
And may i know why?
Upvotes: 1
Views: 101
Reputation: 4139
The assignment of jsoninfo
is happening outside of the for-loop but the assignment of geoinfo
is happening inside of it. You need to aggregate all of the geoloc.attrib
values into a list and convert this to json at the end:
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')
This assumes you actually meant to output a single JSON object as your response instead of two encodings of independent objects separated by a newline character.
Upvotes: 2
Reputation: 11741
You are overwriting geoinfo
every time in your loop. You are not storing all the results. Consider creating an empty list, appending to it, and sending that back as a response
Upvotes: 0