10

I am somewhat new to python and I am wondering what the best way is to generate json in a loop. I could just mash a bunch of strings together in the loop, but I'm sure there is a better way. Here's some more specifics. I am using app engine in python to create a service that returns json as a response.

So as an example, let's say someone requests a list of user records from the service. After the service queries for the records, it needs to return json for each record it found. Maybe something like this:

{records: 
{record: { name:bob, email:[email protected], age:25 } },
{record: { name:steve, email:[email protected], age:30 } }, 
{record: { name:jimmy, email:[email protected], age:31 } }, 
}

Excuse my poorly formatted json. Thanks for your help.

1
  • 11
    I think you're overthinking this. There's a JSON library for Python, just generate the data structure and pass it to json.dumps Commented May 3, 2011 at 15:50

3 Answers 3

18

Creating your own JSON is silly. Use json or simplejson for this instead.

>>> json.dumps(dict(foo=42))
'{"foo": 42}'
Sign up to request clarification or add additional context in comments.

Comments

7

My question is how do I add to the dictionary dynamically? So foreach record in my list of records, add a record to the dictionary.

You may be looking to create a list of dictionaries.

records = []
record1 = {"name":"Bob", "email":"[email protected]"}
records.append(record1)    
record2 = {"name":"Bob2", "email":"[email protected]"}
records.append(record2)

Then in app engine, use the code above to export records as json.

Comments

4

Few steps here.

First import simplejson

from django.utils import simplejson

Then create a function that will return json with the appropriate data header.

def write_json(self, data):
  self.response.headers['Content-Type'] = 'application/json'
  self.response.out.write(simplejson.dumps(data))

Then from within your post or get handler, create a python dictionary with the desired data and pass that into the function you created.

 ret = {"records":{
   "record": {"name": "bob", ...}
   ...
 }
 write_json(self, ret)

2 Comments

My question is how do I add to the dictionary dynamically? So foreach record in my list of records, add a record to the dictionary.
as the original question specifically relates to appengine, it is worth noting that the django library is not automatically available. You need to include a reference to it in your app.yaml stackoverflow.com/questions/11174750/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.