您的位置:首页技术文章
文章详情页

通过Python将Json数据导入MongoDB

【字号: 日期:2022-08-15 13:00:38浏览:47作者:猪猪

问题描述

首先数据是以标准的json格式的文本。然后想要通过python脚本来导入Mongodb中。json

{ 'service': 'http', 'datetime': '2017-03-28 17:23:19', 'starttime': '1490692810', 'endtime': '1490692999', 'port': 80}{ 'service': 'ewall', 'datetime': '2017-03-28 17:23:19', 'starttime': '1490692810', 'endtime': '1490692999', 'port': 1328}

python部分代码:

with open(filen, ’r’) as f:while 1: try:jsonstr = f.readline().strip()# print jsonstr 可以输出整个json的内容if not jsonstr: breaktry: j = json.loads(jsonstr) #这里好像不处理的问题 except: continuejsonlist.append(j) except:break

请问这个情况要怎么解决呢?谢谢

问题解答

回答1:

你这个问题是因为你这个不是标准的json格式,标准的格式应该是这样的

[{ 'service': 'http', 'datetime': '2017-03-28 17:23:19', 'starttime': '1490692810', 'endtime': '1490692999', 'port': 80},{ 'service': 'ewall', 'datetime': '2017-03-28 17:23:19', 'starttime': '1490692810', 'endtime': '1490692999', 'port': 1328}]

第二个你这个数据是按行读的,请告诉我你一行数据到底是什么样子的

回答2:

@sheep3 的回答是对的。

如果你直接把JSON放MongoDB里你可以用mongoimport (https://docs.mongodb.com/manu...

你还想处理数据的话可以用这样的代码:

import jsonfilename = ’test.json’with open(filename, ’r’) as f: content = json.load(f)

如果JSON文件的内容比内存大你应该通过streaming方式把JSON文件打开。你可以用ijson包(https://pypi.python.org/pypi/...)。用法也比较简单:

import ijsonwith open(’test.json’) as fp: objects = ijson.items(fp, 'item') for object in objects:print(object)回答3:

@Christoph 的回答直接点名了更简单及优化的处理方案,学了一招

标签: Python 编程
相关文章: