2016-12-07 129 views
0

字典型我有一組下面的數據:JSON進入蟒蛇

{ 
    "dataFrame": "AB3hqqqpVVVOAAA=", 
    "decrypted": true, 
    "fcnt": 3, 
    "id": 1480528200533, 
    "port": 5, 
    "rssi": -116, 
    "sf_used": 10, 
    "snr": -8.5, 
    "timestamp": "2016-11-30T17:50:00.533Z" 
}, 

{ 
    "dataFrame": "AB3hqqqpVVVOAAA=", 
    "decrypted": true, 
    "fcnt": 5, 
    "id": 1480528235613, 
    "port": 5, 
    "rssi": -119, 
    "sf_used": 10, 
    "snr": -5.8, 
    "timestamp": "2016-11-30T17:50:35.613Z" 
}, 
{ 
    "dataFrame": "AB7hqqqpVVVOAAA=", 
    "decrypted": true, 
    "fcnt": 7, 
    "id": 1480528310609, 
    "port": 5, 
    "rssi": -120, 
    "sf_used": 10, 
    "snr": -8.8, 
    "timestamp": "2016-11-30T17:51:50.609Z" 
}, 
{ 
    "dataFrame": "AB7hqqqpVVVOAAA=", 
    "decrypted": true, 
    "fcnt": 9, 
    "id": 1480528403504, 
    "port": 5, 
    "rssi": -116, 
    "sf_used": 10, 
    "snr": -9.2, 
    "timestamp": "2016-11-30T17:53:23.504Z" 
}, 

我想上述轉換成字典類型:

{ 
    u'dataFrame': 'AB3hqqqpVVVOAAA=', 
    u'decrypted': true, 
    u'fcnt': 3, 
    u'id': 1480528200533, 
    u'port': 5, 
    u'rssi': -116, 
    u'sf_used': 10, 
    u'snr': -8.5, 
    u'timestamp': '2016-11-30T17:50:00.533Z' 
} 

所以,當我嘗試使用INFILE = JSON .load(infile)infile是我的輸入文件,爲什麼我會像ValueError那樣出錯:額外的數據?

回答

1

因爲您的輸入文件是一行中的一些json對象,而不是json對象的列表。解析器將在第一個對象關閉後看到第一個,,並且不知道爲什麼這個逗號在那裏,所以它會產生一個ValueError(這實際上是一個json語法錯誤)。

通過添加單個[]他們周圍像這樣使物體成一個列表:

[{ 
    "dataFrame": "AB3hqqqpVVVOAAA=", 
    "decrypted": true, 
    "fcnt": 3, 
    "id": 1480528200533, 
    "port": 5, 
    "rssi": -116, 
    "sf_used": 10, 
    "snr": -8.5, 
    "timestamp": "2016-11-30T17:50:00.533Z" 
}, 

{ 
    "dataFrame": "AB3hqqqpVVVOAAA=", 
    "decrypted": true, 
    "fcnt": 5, 
    "id": 1480528235613, 
    "port": 5, 
    "rssi": -119, 
    "sf_used": 10, 
    "snr": -5.8, 
    "timestamp": "2016-11-30T17:50:35.613Z" 
}, 
{ 
    "dataFrame": "AB7hqqqpVVVOAAA=", 
    "decrypted": true, 
    "fcnt": 7, 
    "id": 1480528310609, 
    "port": 5, 
    "rssi": -120, 
    "sf_used": 10, 
    "snr": -8.8, 
    "timestamp": "2016-11-30T17:51:50.609Z" 
}, 
{ 
    "dataFrame": "AB7hqqqpVVVOAAA=", 
    "decrypted": true, 
    "fcnt": 9, 
    "id": 1480528403504, 
    "port": 5, 
    "rssi": -116, 
    "sf_used": 10, 
    "snr": -9.2, 
    "timestamp": "2016-11-30T17:53:23.504Z" 
}] 
0

一組JSON對象是不是有效的JSON對象本身。

來表示多個對象正確的方法是在一個JSONArray,這是由表示[obj1, obj2, ...., objn]是每個OBJ可表示的JSON對象(像您的類型的字典)