简体   繁体   中英

Finding Element in json file with python

I've writen a script to scrape a site. In the html of that site i managed to find the json file that I want. That's the json https://www.slamjam.com/on/demandware.store/Sites-slamjam-Site/en_IT/Product-Variation?dwvar_J143632_color=&pid=J143632&quantity=1

In this json I want to find a specific element, by input another element. Let me explain. The part I'm interested in is this:

{
    "attributeId": "size",
    "displayName": "Size",
    "id": "size",
    "swatchable": false,
    "values": [
      {
        "id": "WFOX04-2",
        "description": null,
        "displayValue": "36",
        "value": "WFOX04-2",
        "selected": false,
        "selectable": true,
        "availability": 1,
        "productID": "2000138270021",
        "price": 120,
        "url": "https://www.slamjam.com/on/demandware.store/Sites-slamjam-Site/en_IT/Product-Variation?dwvar_J143632_color=F19-105&dwvar_J143632_size=WFOX04-2&pid=J143632&quantity=1"
      },
      {
        "id": "WFOX04-3",
        "description": null,
        "displayValue": "36.5",
        "value": "WFOX04-3",
        "selected": false,
        "selectable": true,
        "availability": 1,
        "productID": "2000138270038",
        "price": 120,
        "url": "https://www.slamjam.com/on/demandware.store/Sites-slamjam-Site/en_IT/Product-Variation?dwvar_J143632_color=F19-105&dwvar_J143632_size=WFOX04-3&pid=J143632&quantity=1"

I want to input a "displayValue" like '36', and if the script can find that value it has to print the "productID". I searched on this forum, googled and tried a lot but failed every time. The last code I wrote is this:

from jsondb.db import Database 
data = Database('/Users/MIKE/Desktop/EIS_BOT/File.json')
for id in data['sizes']:
if element['displayValue'] == '36':
    print('36 in stock')
    print(element['productID'])
    break
else:
    print ('36 not in stock')

Thanks. Edit: the code isn't all here obviously, it's much more, but it perfectly work until this point

try changing this:

if element['displayValue'] == '36':

to

if '36' in element['displayValue']:

this will return any string that has 36 in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM