Reputation: 17
I am trying to format the data that is being scraped from my API. It prints in JSON format as coded. However, my question is how can I format it to make it print data like this:
Product ID: 123456789
Physical Quantity: 20
Quantity Available: 20
At the moment, it prints such as this. It asks the user to input a product ID and then goes to the API to get product information.
{
"payload": [
{
"productId": "10229480",
"quantityPhysical": 20,
"quantityAvailable": 20
}
]
}
The Python code is as follows:
import json
import requests
from colorama import Fore, Style
# getting data from source
get_data = input(Fore.LIGHTRED_EX + "Please enter a product ID to check stock level: ")
beep = requests.get("https://api.mywebsite.co.uk/shop/api/productsStock/" + get_data)
# pretty printing data
pretty_data = json.dumps(beep.json(), indent=4)
print(pretty_data)
Upvotes: 1
Views: 36
Reputation: 54148
You may iterate on the dict data['payload'][0]
# beep = requests.get("https://api.mywebsite.co.uk/shop/api/productsStock/" + get_data)
# data = beep.json() # use that lines for real use
data = {
"payload": [
{
"productId": "10229480",
"quantityPhysical": 20,
"quantityAvailable": 20
}
]
}
for key, val in data['payload'][0].items():
key_fmt = " ".join([x.capitalize() for x in re.findall(r"([A-Z]?[a-z]+)", key)])
print(f"{key_fmt}: {val}")
Upvotes: 1