首頁  >  問答  >  主體

通过Python将Json数据导入MongoDB

首先数据是以标准的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:
                    break
                try:
                    j = json.loads(jsonstr) #这里好像不处理的问题
                    
                except:
                    continue
                jsonlist.append(j)
            except:
                break

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

怪我咯怪我咯2741 天前489

全部回覆(3)我來回復

  • 阿神

    阿神2017-04-18 10:31:42

    你這個問題是因為你這個不是標準的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
    }]

    第二個你這個資料是照行讀的,請告訴我你一行資料到底是什麼樣子的

    回覆
    0
  • 黄舟

    黄舟2017-04-18 10:31:42

    @sheep3 的答案是對的。

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

    你還想處理資料的話可以用這樣的程式碼:

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

    如果JSON檔案的內容比記憶體大你應該透過streaming方式把JSON檔案打開。你可以用ijson包(https://pypi.python.org/pypi/...)。用法也比較簡單:

    import ijson
    
    with open('test.json') as fp:
        objects = ijson.items(fp, "item")
        for object in objects:
            print(object)

    回覆
    0
  • 迷茫

    迷茫2017-04-18 10:31:42

    @Christoph 的回答直接點名了更簡單及優化的處理方案,學了一招

    回覆
    0
  • 取消回覆