按某个键对JSON文件进行排序

时间:2017-07-23 15:25:13

标签: python json sorting

我在Python编码。

我有一个内容<{p>的carV.json文件

{"CarValue": "59", "ID": "100043" ...}
{"CarValue": "59", "ID": "100013" ...}
...

如何将文件内容排序为

{"CarValue": "59", "ID": "100013" ...}
{"CarValue": "59", "ID": "100043" ...}
...

使用&#34; ID&#34;排序的关键?

我尝试了不同的方法来读取和执行排序,但总是得到错误,例如&#34;没有排序属性&#34;或者&#39; &#34;的unicode&#39;对象没有属性&#39; sort&#39;&#34;。

2 个答案:

答案 0 :(得分:5)

有几个步骤:

这里有一些代码可以帮助您入门:

import json, operator

s = '''\
[
  {"CarValue": "59", "ID": "100043"},
  {"CarValue": "59", "ID": "100013"}
]
'''

data = json.loads(s)
data.sort(key=operator.itemgetter('ID'))
print(json.dumps(data, indent=2))

输出:

[
  {
    "CarValue": "59",
    "ID": "100013"
  },
  {
    "CarValue": "59",
    "ID": "100043"
  }
]

对于您的应用,请打开输入文件并使用json.load()代替json.loads()。同样,打开输出文件并使用json.dump()代替json.dumps()。您也可以删除 indent 参数,这只是为了使输出看起来格式化。

答案 1 :(得分:2)

简单且可能更快,以防大数据 - pandas.DataFrame.to_json

>>> import pandas as pd
>>> unsorted = pd.read_json("test.json")
>>> (unsorted.sort_values("ID")).to_json("sorted_test.json")
>>> sorted = unsorted.sort_values("ID")
>>> sorted
   CarValue      ID
1        59  100013
0        59  100043
>>> sorted.to_json("n.JSON")