如何使用Python将Ansible std_输出JSON插入MongoDB
我正在我的剧本中运行以下任务如何使用Python将Ansible std_输出JSON插入MongoDB,python,json,mongodb,ansible-facts,Python,Json,Mongodb,Ansible Facts,我正在我的剧本中运行以下任务 - name: get system info shell: uname -r register: uname_out - debug: var=uname_out when: conn_out is success - name: copy copy: content={{ uname_out.stdout_lines }} dest={{inventory_hostname}}.json 我得到的JSON输出如下 ["rh
- name: get system info
shell: uname -r
register: uname_out
- debug: var=uname_out
when: conn_out is success
- name: copy
copy:
content={{ uname_out.stdout_lines }} dest={{inventory_hostname}}.json
我得到的JSON输出如下
["rhel", "linux", "7", "basevesrion"]
为了将这些数据插入MongoDB,我编写了如下脚本
import json
from pymongo import MongoClient
fileName = "data.json"
print(fileName)
client = MongoClient('10.*.*.*',27017)
db = client['test']
collection_cmdbFact = db['facts']
with open(fileName,'r') as data_file:
data_json = json.loads(data_file.read())
collection.insert_one(data_json)
client.close()
我得到了这个错误
TypeError:文档必须是dict、bson.son.son、bson.raw\u bson.RawBSONDocument的实例,或者是从collections.MutableMapping继承的类型
有人能告诉我如何插入这些数据吗?我做了一个快速测试。这很好:
collection.insert_one(json.loads("{\"a\":1}"))
这将返回您注意到的确切错误:
collection.insert_one(json.loads("[{\"a\":1},{\"a\":2}]"))
如果您的文件包含一系列文档,则可能需要使用insert\u many
:
collection.insert_many(json.loads("[{\"a\":1},{\"a\":2}]"))