Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python将Ansible std_输出JSON插入MongoDB_Python_Json_Mongodb_Ansible Facts - Fatal编程技术网

如何使用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}]"))