Reputation: 2362
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
Upvotes: 0
Views: 797
Reputation: 3513
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)
Upvotes: 3
Reputation: 1817
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
Upvotes: 3