python通過對字典的排序,對json字段進行排序的實例
如下所示:
dic = dict() dic['a'] = 1 dic['b'] = 2 dic['c'] = 3 print(dic.items()) import json jsons = json.dumps(dic) print(jsons)
結(jié)果:
dic is: dict_items([('c', 3), ('b', 2), ('a', 1)])
jsons: {"c": 3, "b": 2, "a": 1}
通過使用collecions,進行排序。collections是一個python的內(nèi)建模塊。
import collections dic = collections.OrderedDict() # dic = dict() dic['a'] = 1 dic['b'] = 2 dic['c'] = 3 print("dic is:",dic.items()) import json jsons = json.dumps(dic) print("jsons:",jsons)
結(jié)果:
dic is: odict_items([('a', 1), ('b', 2), ('c', 3)])
jsons: {"a": 1, "b": 2, "c": 3}
補充拓展:對JSON集合 某個鍵進行升序/降序排列
我就廢話不多說了,直接上代碼吧
$(document).ready(function () { //對json進行降序排序函數(shù) var colId="age" var desc = function(x,y) { return (x[colId] < y[colId]) ? 1 : -1 } //對json進行升序排序函數(shù) var asc = function(x,y) { return (x[colId] > y[colId]) ? 1 : -1 } var arr2 = [ {name:"kitty", age:12}, {name:"sonny", age:9}, {name:"jake", age:13}, {name:"fun", age:24} ]; document.writeln("按age進行升序排序:<br>"); arr2.sort(asc); //升序排序 document.writeln(JSON.stringify(arr2)); document.writeln("<br>按age進行降序排序:<br>"); arr2.sort(desc); //降序排序 document.writeln(JSON.stringify(arr2)); });
以上這篇python通過對字典的排序,對json字段進行排序的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Pycharm打印大數(shù)據(jù)文件顯示不全的解決方法
這篇文章主要介紹了Pycharm打印大數(shù)據(jù)文件顯示不全的解決方法,昨晚寫了個小爬蟲,簡單分析下發(fā)現(xiàn)可以修改請求的url,直接獲取所有目標的數(shù)據(jù),想先打印在控制臺看看,發(fā)現(xiàn)打印的數(shù)據(jù)不全,所以本文記錄了一下解決方法,需要的朋友可以參考下2024-03-03Django Auth應(yīng)用實現(xiàn)用戶身份認證
Django Auth 應(yīng)用一般用在用戶的登錄注冊上,用于判斷當前的用戶是否合法。本文將介紹Auth的另一個功能,即認證用戶身份,感興趣的同學(xué)可以關(guān)注一下2021-12-12