如何使用Python对JSON或文本进行排序
如何使用Python对JSON或文本进行排序 这是我的密码如何使用Python对JSON或文本进行排序,python,json,Python,Json,如何使用Python对JSON或文本进行排序 这是我的密码 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
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)
对请求的响应
[
{
"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
},
]
我想按响应中的“数量”值降序排列数字。
请帮助我提供有关如何进行的建议,谢谢您需要在
转储()之前对响应进行排序
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)
这回答了你的问题吗?不要使用json
作为名称,因为您重写了模块json
,不要转储response.json()
,因为它将生成一个json字符串。使用从response.json()