0

I tried to export data to csv from Mongodb by using Python. I am getting error: "TypeError: can only join an iterable"

mongodb data sample:

{ "_id" : ObjectId("51dc52fec0d988a9547b5201"),
  "hiringManagerIds" : [ 
        "529f5ad1030dedd0a88ed7be", 
        "529f5ad1030dedd0a88ed7bf"
    ]
  }

Python script:

import codecs
import csv
cursor = db.jobs.find( {}, {'_id': 1, 'hiringManagerIds': 1})
with codecs.open('jobs_array.csv', 'w', encoding ='utf-8') as outfile:
    fields = ['_id', 'hiringManagerIds']    
    write = csv.writer(outfile)
    write.writerow(fields)
    for x in cursor:
        write.writerow((x["_id"], u','.join(x.get('hiringManagerIds'))))

error messages:

Traceback (most recent call last):
File "<stdin>", line 6, in <module>
TypeError: can only join an iterable

I want to remove u letters so I use u.join in the script. the hiringManagerIds filed is missing in some document, so I use get. If I don't add u''.join in the script, it works, but it brings u letters in the csv file. I tried many different ways, but it did not work. Appreciate for any helps. thanks.

4
  • What does print x.get('hiringManagerIds') do? Commented Jul 18, 2017 at 18:36
  • This code would not run: the indentation on the last line of the first block is not correct? Commented Jul 18, 2017 at 18:40
  • it gives value of hiringmanagerids: [u'529f5ad1030dedd0a88ed7be', u'529f5ad1030dedd0a88ed7bf'] thanks Commented Jul 18, 2017 at 18:41
  • @philip-adler, thanks, when copied to here, I forgot to put space before last line. Commented Jul 18, 2017 at 18:44

1 Answer 1

1

The error stems from one of the documents not having hiringManagerIds. If this is undefined, at present your code returns None into the join method, which requires an iterable (None is not an iterable).

You should check if the key is present in the dictionary first:

if 'hiringManagerIds' in x.keys():
    write.writerow((x["_id"], u','.join(x.get('hiringManagerIds'))))
else:
    write.writerow((x["_id"], '')))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. @Philip Adler. It worked. It removes the u letters perfectly. I like your solution.

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.