简体   繁体   中英

python - if availability is there, then print it out, else don't print it out

So I am playing a bit with json and I have been stuck into a code where I print out items['ids']

which gives me a value of:

[
  {
    'id': '11891',
    'availability': 'IsNotThere',
  },
  {
    'id': '11892',
    'availability': 'IsThere',
  },
  {
    'id': '11893',
    'availability': 'IsThere',
  },
  {
    'id': '11894',
    'availability': 'IsNotThere',
  },
  {
    'id': '11895',
    'availability': 'IsNotThere',
  },
  {
    'id': '11896',
    'availability': 'IsNotThere',
  },
  {
    'id': '11897',
    'availability': 'IsNotThere',
  },
  {
    'id': '11898',
    'availability': 'IsNotThere',
  },
  {
    'id': '11899',
    'availability': 'IsNotThere',
  },
  {
    'id': '11900',
    'availability': 'IsNotThere',
  }
]

And I have been trying to figure out if it should be a for-loop including this problem. However I didn't come anywhere and here I am. Now I have been stuck and wondering how I can print out the ID where the avaliability "IsThere" otherwise just skip it?

EDIT:

id_list = [i for i in products['skus'] if i.get("id")]

for i in id_list:
   if i['availability'] == 'IsThere':
       print(i)

If you just care about the id , and you can fetch by its name id . and you can do it like :

id_list = [i for i in sample if i.get("availability") == 'IsThere']

To print it out, just simple loop and print it.

for i in id_list:
    print(i)

If you have a JSON object you can just loop it and check the fields using the fieldname as index:

for line in json:
    if(line['availability'] == "IsThere"):
       # if available -> print the id
       print(line['id'))

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