通過Python將Json數(shù)據導入MongoDB
問題描述
首先數(shù)據是以標準的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}]
第二個你這個數(shù)據是按行讀的,請告訴我你一行數(shù)據到底是什么樣子的
回答2:@sheep3 的回答是對的。
如果你直接把JSON放MongoDB里你可以用mongoimport (https://docs.mongodb.com/manu...
你還想處理數(shù)據的話可以用這樣的代碼:
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 的回答直接點名了更簡單及優(yōu)化的處理方案,學了一招
相關文章:
1. css3 - [CSS] 動畫效果 3D翻轉bug2. python小白的基礎問題 關于while循環(huán)的嵌套3. MySQL客戶端吃掉了SQL注解?4. javascript - JS設置Video視頻對象的currentTime時出現(xiàn)了問題,IE,Edge,火狐,都可以設置,反而chrom卻...5. 求大神幫我看看是哪里寫錯了 感謝細心解答6. javascript - 百度echarts series數(shù)據更新問題7. python - Django分頁和查詢參數(shù)的問題8. javascript - 圖片能在網站顯示,但控制臺仍舊報錯403 (Forbidden)9. php自學從哪里開始?10. phpstady在win10上運行
