0

I need to create a json array like ["a", "b", "c", "d"]

I'm trying to create it as follows

import json

with open('djs.json', 'w') as outfile:
    for dj in DJ.objects.all():
        json.dump(str(dj), outfile, separators=(',', ': '))

This creates something like "a","b","c","d"

What would be the correct way to do this?

4
  • What is DJ.objects.all() ? Commented Jun 25, 2014 at 18:42
  • DJ.objects are objects of my Django model. Commented Jun 25, 2014 at 18:43
  • What does it contain? Commented Jun 25, 2014 at 18:43
  • dj is a Django model object that contains all the information regarding a DJ. dj evaluates to the DJ name if that's what you are asking. Commented Jun 25, 2014 at 18:45

1 Answer 1

3

How about this:

lst = [str(dj) for dj in DJ.objects.all()]    
with open('data.txt', 'w+') as outfile:
    json.dump(lst, outfile)

if your __unicode__ is a single field, You could even do

json_dump = json.dump(list(Dj.objects.values_list('field', flat=True)))
Sign up to request clarification or add additional context in comments.

4 Comments

This is giving me a blank json file for some reason.
do you want to return a json to a respond to a request ?
No, I need to make a JSON file with a JSON array containing the name of all the DJs.
Ok. check the edit. You should have the json in a file called data.txt

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.