0

I have a file having key value pairs in the following format

key1:value1, key2:value2 ...

I want to load the file into mongodb using pymongo but I have been failing. I have tried json.loads but still not successful.

Is there some way to have some thing like

for records in file
   for each key, value in record
      Insert key, value for that specific record_id
4
  • You can split it first by the comma character (for each key-value pair) and then for each pair split by the colon character : Commented Dec 24, 2013 at 10:10
  • splitting is not a problem, I am able to insert data to mongodb Commented Dec 24, 2013 at 10:11
  • So then what is your question about? You are able to insert the data? Commented Dec 24, 2013 at 10:12
  • I have made an edit to the original question Commented Dec 24, 2013 at 10:17

2 Answers 2

3

You have to store your values as json format in your files like

{
    "key1": "value1",
    "key2": "value2"
}

In myself I stored above it in demo.txt file.

Then I load using json.load as following

import json

txt = open('demo.txt', 'rb')
data = json.load(txt)

and the result of above is like

>> {u'key1': u'value1', u'key2': u'value2'}

for json format help

Sign up to request clarification or add additional context in comments.

Comments

3

You can of course store as JSON (see @Syed answer)

but if changing that file is not an option, you can split using ',' and ':', and create a dictionary from that:

with open('your_file.txt', 'r') as file:
    line = file.readline()
    to_insert = {key.trim(): value.trim() for key, value in (pair.split(':') for pair in line.split(','))}
    collection.save(to_insert)

Comments

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.