Bevezető: JSON feldolgozása

Van egy adathalmazunk, ami megegyezik a link válaszával, kimentve egy json fájlba.

Feladat: kiválogatni az id, title, price, discountPercentage mezőket és ezek alapján kiszámolni a newPrice mezőt. (Az eredeti ár és az akció mértékének használatával)

import json

file = ""

with open("products.json", "r", encoding="utf8") as f:
    file = f.read()

adat = json.loads(file)

szurt = []

for p in adat["products"]:
    p_uj = {
        "id": p["id"],
        "title": p["title"],
        "price": p["price"],
        "discountPercentage": p["discountPercentage"]
    }
    new_price = round(p["price"] * (100 - p["discountPercentage"]) / 100, 2)
    p_uj["newPrice"] = new_price
    szurt.append(p_uj)

szurt_szoveg = json.dumps(szurt)

with open("szurt3.json", "w", encoding="utf8") as f:
    f.write(szurt_szoveg)

API lekérdezés

# pip install requests
import requests

url = "https://dummyjson.com/products"

response = requests.get(url).json()

print(response)