-2

How to sorting JSON or Text with Python

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

  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – buran Feb 23 '21 at 13:37
  • 1
    don't use `json` as name, because you override the module `json` and don't dump the `response.json()` because it will yield a JSON string. Work with the list of dicts that you get from `response.json()` – buran Feb 23 '21 at 13:39

1 Answers1

1

You need to sort the response before dumps()-ing it

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)
rdas
  • 20,604
  • 6
  • 33
  • 46