JSON成为python中的Dictionary类型

时间:2016-12-07 17:30:25

标签: python json dictionary

我有一组以下数据:

search() {
    this.sub = this.nodeService.getNodes({ q: this.q })
      .subscribe(
        res => {
          this.nodes = this.filteredNodes = res;
          this.totalItems = this.nodes.length;
        }
    );
  }

我正在尝试将上面的内容转换为字典类型:

{
    "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"
}, 

所以当我尝试使用infile = json.load(infile),其中infile是我的输入文件时,为什么我会收到ValueError之类的错误:额外的数据?

2 个答案:

答案 0 :(得分: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"
}]

答案 1 :(得分:0)

一组JSON对象本身不是有效的JSON对象。

表示多个对象的正确方法是在JSONArray中,它由[obj1, obj2, ...., objn]表示,每个obj都是一个可表示的JSON对象(如你的dicts)