通過Python將Json數(shù)據(jù)導(dǎo)入MongoDB
問題描述
首先數(shù)據(jù)是以標(biāo)準(zhǔn)的json格式的文本。然后想要通過python腳本來導(dǎo)入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 可以輸出整個(gè)json的內(nèi)容if not jsonstr: breaktry: j = json.loads(jsonstr) #這里好像不處理的問題 except: continuejsonlist.append(j) except:break
請(qǐng)問這個(gè)情況要怎么解決呢?謝謝
問題解答
回答1:你這個(gè)問題是因?yàn)槟氵@個(gè)不是標(biāo)準(zhǔn)的json格式,標(biāo)準(zhǔn)的格式應(yīng)該是這樣的
[{ '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}]
第二個(gè)你這個(gè)數(shù)據(jù)是按行讀的,請(qǐng)告訴我你一行數(shù)據(jù)到底是什么樣子的
回答2:@sheep3 的回答是對(duì)的。
如果你直接把JSON放MongoDB里你可以用mongoimport (https://docs.mongodb.com/manu...
你還想處理數(shù)據(jù)的話可以用這樣的代碼:
import jsonfilename = ’test.json’with open(filename, ’r’) as f: content = json.load(f)
如果JSON文件的內(nèi)容比內(nèi)存大你應(yīng)該通過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 的回答直接點(diǎn)名了更簡單及優(yōu)化的處理方案,學(xué)了一招
相關(guān)文章:
1. python - beautifulsoup獲取網(wǎng)頁內(nèi)容的問題2. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題3. docker鏡像push報(bào)錯(cuò)4. docker - 如何修改運(yùn)行中容器的配置5. docker-machine添加一個(gè)已有的docker主機(jī)問題6. fragment - android webView 返回后怎么禁止重新渲染?7. docker不顯示端口映射呢?8. android studio總是在processes running好久9. dockerfile - [docker build image失敗- npm install]10. angular.js - Angular 2 + Django構(gòu)建的Web應(yīng)用, 如何合理搭配 ?
