URLからJSONファイルを取得し、それを変数に代入してテスト用に出力できます。それをMongoDBに挿入するのに本当に問題があります。ここに私のコードです。Python Mongodb、TypeError:ドキュメントはdictのインスタンスでなければなりません。bson.son.SON、bson.raw_bson
import urllib.request, json
from datetime import datetime
import pymongo
from pymongo import *
client = MongoClient()
db = client['2marte71']
posts = db.posts
with urllib.request.urlopen("http://southamptonstudentrooms.com/IoT/arduinoData.php") as url:
data = json.loads(url.read().decode())
print(data) # just to test json data
result = posts.insert_one(data).inserted_id
とシェル出力:
[{'temp': '24', 'time': '00:35:17', 'ldr': '40', 'hum': '44'}, {'temp': '24', 'time': '00:37:21', 'ldr': '40', 'hum': '44'}, {'temp': '24', 'time': '00:39:25', 'ldr': '40', 'hum': '44'}, {'temp': '23', 'time': '00:00:13', 'ldr': '50', 'hum': '46'}, {'temp': '23', 'time': '00:02:16', 'ldr': '39', 'hum': '46'}, {'temp': '23', 'time': '00:04:20', 'ldr': '39', 'hum': '46'}, {'temp': '23', 'time': '00:06:24', 'ldr': '39', 'hum': '46'}, {'temp': '23', 'time': '00:08:28', 'ldr': '39', 'hum': '46'}, {'temp': '23', 'time': '00:10:31', 'ldr': '39', 'hum': '46'}, {'temp': '23', 'time': '00:12:35', 'ldr': '39', 'hum': '46'}, {'temp': '23', 'time': '00:14:39', 'ldr': '50', 'hum': '46'}, {'temp': '23', 'time': '00:16:43', 'ldr': '39', 'hum': '46'}, {'temp': '23', 'time': '00:18:46', 'ldr': '36', 'hum': '46'}, {'temp': '23', 'time': '00:20:50', 'ldr': '36', 'hum': '45'}, {'temp': '23', 'time': '00:22:54', 'ldr': '37', 'hum': '45'}, {'temp': '23', 'time': '00:24:58', 'ldr': '37', 'hum': '45'}, {'temp': '23', 'time': '00:27:01', 'ldr': '38', 'hum': '45'}, {'temp': '24', 'time': '00:29:05', 'ldr': '41', 'hum': '45'}, {'temp': '24', 'time': '00:31:09', 'ldr': '41', 'hum': '44'}, {'temp': '24', 'time': '00:33:13', 'ldr': '40', 'hum': '44'}]
Traceback (most recent call last):
File "testPythonJson.py", line 11, in <module>
result = posts.insert_one(data).inserted_id
File "/usr/local/lib/python3.5/dist-packages/pymongo/collection.py", line 664, in insert_one
common.validate_is_document_type("document", document)
File "/usr/local/lib/python3.5/dist-packages/pymongo/common.py", line 409, in validate_is_document_type
"collections.MutableMapping" % (option,))
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping