简体   繁体   English

如何使用 Python 对 JSON 或文本进行排序

[英]How to sorting JSON or Text with Python

How to sorting JSON or Text with Python如何使用 Python 对 JSON 或文本进行排序

This my code这是我的代码

import requests
import json

response = requests.get('https://dataapi.moc.go.th/export-commodity-countries?year=2017&month=12&com_code=101010200&limit=3', verify=False)
json = json.dumps(response.json(), sort_keys=True, indent=4)

print(json)

response from request请求的响应

[
    {
        "acc_quantity": 446172.38,
        "acc_value_baht": 11962105709.0,
        "acc_value_usd": 354576307.0,
        "country_code": "US",
        "country_name_en": "U.S.A.",
        "month": 12,
        "quantity": 40907.66,
        "year": 2017
    },
    {
        "acc_quantity": 247355.84,
        "acc_value_baht": 6308794603.0,
        "acc_value_usd": 187646852.0,
        "country_code": "CN",
        "country_name_en": "CHINA",
        "month": 12,
        "quantity": 55167.72,
        "year": 2017
    },
    {
        "acc_quantity": 179555.35,
        "acc_value_baht": 4767877318.0,
        "acc_value_usd": 140840413.0,
        "country_code": "HK",
        "country_name_en": "HONG KONG",
        "month": 12,
        "quantity": 16576.98,
        "year": 2017
    },
]

I want to sorting numbers in descending order by "quantity" value from response.我想按响应中的“数量”值对数字进行降序排序。 please help me advice on how to, thanks请帮我建议如何做,谢谢

You need to sort the response before dumps() -ing it您需要在dumps() -ing之前对响应进行排序

import requests
import json

response = requests.get('https://dataapi.moc.go.th/export-commodity-countries?year=2017&month=12&com_code=101010200&limit=3', verify=False)
# get the data
response_data = response.json()
# sort it based on quantity
response_data.sort(key=lambda entry: entry['quantity'])
# now print
json_str = json.dumps(response_data, sort_keys=True, indent=4)

print(json_str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM