当前位置:  Json知识分享 > 正文

python通过对字典的排序,对json字段进行排序的实例

今天小编就为大家分享一篇python通过对字典的排序,对json字段进行排序的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

如下所示:

dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3
print(dic.items())

import json
jsons = json.dumps(dic)
print(jsons)

结果:

dic is: dict_items([('c', 3), ('b', 2), ('a', 1)])
jsons: {"c": 3, "b": 2, "a": 1}

通过使用collecions,进行排序。collections是一个python的内建模块。

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)

结果:

dic is: odict_items([('a', 1), ('b', 2), ('c', 3)])
jsons: {"a": 1, "b": 2, "c": 3}

补充拓展:对JSON集合 某个键进行升序/降序排列

我就废话不多说了,直接上代码吧

$(document).ready(function () { 
  //对json进行降序排序函数 
  var colId="age" 
  var desc = function(x,y) 
  { 
    return (x[colId] < y[colId]) ? 1 : -1 
  } 
  //对json进行升序排序函数 
  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字段进行排序的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

涵涵
Json知识小博士
7.1k 经验值   |   10.8k 粉丝
JSON1.CN | 专业的在线JSON解析格式化及在线开发工具网站 | Json格式化 | PNG素材下载 | 二维码生成工具 | unix时间戳 | IP地址查询 | urlencode | 在线工具
Copyright © 1998 - 2020 JSON1.CN. All Rights Reserved JSON1.CN Json在线解析格式化 版权所有 京ICP备19059560号-7