在龙卷风处理程序中对json_util_dumps中的项目进行排序

时间:2018-10-18 04:12:22

标签: python json tornado

我想输出以下内容(按我的脚本中的顺序排序)。

{"data": [
    { "cid": "CG138712",
      "mac": "24-A4-3C-F6-51-21",
      "category": "CPE- E",
      "last_seen": "2017-12-11 12:42:10",                                                 
       "cpe-o": {"cid": "CS247314",
                 "mac":"80-2A-A8-7E-1D-8E",
                 "category": "CPE-O", 
                 "last_seen": "2018-05-14 15:28:42", 
               }
    }]
}

但是我的代码保持这样的输出。

{"data": [
        { "cid": "CG138712",
          "category": "CPE- E",                                                 
           "cpe-o": {"cid": "CS247314",
                     "last_seen": "2018-05-14 15:28:42", 
                     "category": "CPE-O", 
                     "mac":"80-2A-A8-7E-1D-8E"   
                   }
            "mac": "24-A4-3C-F6-51-21",
            "last_seen": "2017-12-11 12:42:10",
        }]
    }

这就是我在脚本中实现的方式!

    cpeo_dict = dict(......)  
    doc = {"cid": document['cid'],"mac": document['mac'],"category": document['category'],"last_seen": document['last_seen'].strftime("%Y-%m-%d %H:%M:%S"),"cpe-o": cpeo_dict}
   docs_uplink.append(doc)
   dumped = json_util.dumps(dict(data=docs_uplink))

我找不到如何在json_util.dumps函数中添加参数,我只找到json.dumps的sort和OrderedDict。

1 个答案:

答案 0 :(得分:0)

Python字典不保留顺序。字典中有一个特殊的类来保存顺序-collections.OrderedDict。您需要使用Note来代替dict

示例:

OrderedDict