mardi 27 avril 2021

How can I even use the'else' syntax in Python?

I am reading data from a JSON file to check the existence of some values.

In the JSON structure below, I try to find adomain from the data in bid and check if there is a cat value, which is not always present.

How do I fix it in the syntax below?

import pandas as pd
import json
    
path = 'C:/MyWorks/Python/Anal/data_sample.json'
    
records = [json.loads(line) for line in open(path, encoding='utf-8')]
    
adomain = [
    rec['win_res']['seatbid'][0]['bid'][0]['adomain']
    for rec in records
    if 'adomain' in rec
]

Here is a data sample:

      "win_res": {
        "id": "12345",
        "seatbid": [
          {
            "bid": [
              {
                "id": "12345",
                "impid": "1",
                "price": 0.1,
                "adm": "",
                "adomain": [
                  "adomain.com"
                ],
                "iurl": "url.com",
                "cid": "11",
                "crid": "11",
                "cat": [
                  "IAB12345"
                ],
                "w": 1,
                "h": 1
              }
            ],
            "seat": "1"
          }
        ],
      },

As a result, the adomain value exists unconditionally, but the cat value may not be present sometimes.

So, if cat exists in adomain, I want to express adomain and cat in this way, but if there is no adomain, the cat value, how can I do it?

Aucun commentaire:

Enregistrer un commentaire