下面是一个Python的代码示例,使用Counter类来统计JSON中字符串出现的次数,并根据键的顺序进行排序:
import json
from collections import Counter
# 示例的JSON数据
json_data = '{"foo": "abc", "bar": "def", "baz": "abc", "qux": "abc"}'
# 将JSON数据解析为字典
data = json.loads(json_data)
# 统计字符串出现的次数
counter = Counter(data.values())
# 根据键的顺序进行排序
sorted_strings = sorted(counter.items(), key=lambda x: list(data.keys()).index(x[0]))
# 输出排序结果
for string, count in sorted_strings:
print(f'{string}: {count}')
输出结果为:
abc: 3
def: 1
这里使用Counter类来统计字符串出现的次数,并使用lambda函数作为排序的键函数,根据键的顺序进行排序。最后输出按照键的顺序排序的字符串和对应的出现次数。
下一篇:按照键的特定值过滤对象的数组列表