Home > Blockchain >  How return only object contain string from XML/JSON URL
How return only object contain string from XML/JSON URL

Time:10-27

If there anyone can help me get only string i need from parsing URL:

import requests 
import json

def get_stock(sku):
    params = {'ItemId': sku}
    base_url = 'http://10.0.0.25/api/GetSku?ItemId='
    response = requests.get(base_url, params=params)
    json_parsed = json.loads(response.read)
     
    return json_parsed



    
print(get_stock(101025HRLONDON))

The output is:

[
   {
        "ItemId": "101025HRLONDON",
        "Site": "12",
        "Warehouse": "17",
        "availablePhysical": 1.0
    },
    {
        "ItemId": "101025HRLONDON",
        "Site": "33",
        "Warehouse": "33",
        "availablePhysical": 1.0
    },
    {
        "ItemId": "101025HRLONDON",
        "Site": "12",
        "Warehouse": "34",
        "availablePhysical": 1.0
    },
    {
        "ItemId": "101025HRLONDON",
        "Site": "77",
        "Warehouse": "42",
        "availablePhysical": 1.0
    }
]

The code works well and returns all products stock by ItemID.

But my question is how I can return an only object that contains : "Site":"12"

Thank you!

CodePudding user response:

Replace:

return json_parsed

By:

if any(i['Site'] == '12' for i in json_parsed):
    return json_parsed

CodePudding user response:

You can filter the list using the key you want. The function you've written is correct, you only need to manipulate the returned data.

filtered_stocks = list(filter(lambda x: x['Site']=="12", get_stock("101025HRLONDON"))
print(filtered_stocks)

CodePudding user response:

something like the below

import requests 
from typing import List,Dict


def get_stock(sku:str,site_id:str)-> List[Dict]:
    base_url = 'http://10.0.0.25/api/GetSku?ItemId='
    response = requests.get(base_url, params={'ItemId': sku})
    if response.status_code == 200:
      return [item for item in response.json() if item['Site'] == site_id]
    else:
      return None
  • Related