-2

How can I serialize the entire result set from a search api query on GAE into json? I'm using python and the standard library.

Ive got my results :

index = search.Index(name=Myindex)
query_string = "amount > 0"         
results = index.search(query_string)
json_results = {}

I was trying to iterate through them and construct a json output bit by bit,

for i in results:
    x = {'result': 
        {'name' : i.field('name').value,
        'value' : i.field('value').value
        'geo' : i.field('location').value
        }}
    json_results = dict(list(json_results)+list(x))

json.dump(json_results,self.response.out)

but I'm totally new to coding and just teaching myself as I go along on this project...Ive tried all manner of variation in the last couple of days, to no avail. There must be a simple way.

user16928
  • 3
  • 2

1 Answers1

0

You are on the right path, but there are a few errors in your code, I assume you want to pass back an ordered list of dictionaries holding the results. At the moment you are constructing a dict of dicts, and the outer dictionary all share the same key "results" which means you will end up with a single entry.

json_results = []
for i in results:
    x = {'name' : i.field('name').value,
        'value' : i.field('value').value
        'geo' : i.field('location').value}

    json_results.append(x)

self.response.write(json.dumps(json_results,self.response.out))

In addition you will want to set your content type in the header appropriately. See SO question What is the correct JSON content type? for correct types.

Community
  • 1
  • 1
Tim Hoffman
  • 12,908
  • 1
  • 15
  • 28
  • Splendid, many thanks for your asistance, and I got my self.response.headers['Content-Type'] = 'application/json' too – user16928 May 27 '14 at 13:55