1

In my Python script, I'm working with JSON files but in some files I have an input "racecards" and in some files I have "raceCards".

How can I ask to Python to use the two cases?

My script:

for file1 in FILE:
    with open(path + '%s' %file1,encoding='utf-8') as f1:
        INPUT1 = json.load(f1)

        DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]
        X = list(DATA.values())

        for x in X[0]:
            ENTRY = []
            for h1 in header1.split(','):
                ENTRY.append(x[h1])

            Entry = [str(i) for i in ENTRY]
            towrite = ','.join(Entry)
            print(towrite,file=output1)
tripleee
  • 175,061
  • 34
  • 275
  • 318
Paul R
  • 105
  • 4
  • You'll have to check. `if "racecards" in INPUT1["pageProps"]["initialState"]:`. It's not recommended to use ALL CAPS for variable names. – Tim Roberts Mar 13 '22 at 07:22
  • 1
    Your terminology was slightly confused, so I edited the wording. When something is "case sensitive", it means it's sensitive to changes in case, i.e. A is different from a. It's not the case iteslf that is being sensitive or insensitive, and, just to spell it out, being insensitive to case distinctions means to regard the two as equal. – tripleee Mar 13 '22 at 07:23
  • 1
    If you can't predict ahead of time which keywords use which form, you'll have to normalize them. The simplest normalization is to convert everything to lower case. You then obviously lose any knowledge about whether the original input used upper case somewhere. – tripleee Mar 13 '22 at 07:25
  • you say that I have to convert all json file to the same case ? – Paul R Mar 13 '22 at 07:28
  • Thanks for sharing this ! I will try to apply this. I guess that I have to use if statement with : DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"] and DATA = INPUT1["pageProps"]["initialState"]["racecards"]["races"]. But when trying that, message "KeyError: 'racecards' appear – Paul R Mar 13 '22 at 07:33

1 Answers1

2

One way is that you can simply use a try & except to implement it.

instead of:

DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]

Replace with:

try:
   DATA = INPUT1["pageProps"]["initialState"]["raceCards"]["races"]
except Exception ignored:
   DATA = INPUT1["pageProps"]["initialState"]["racecards"]["races"]
Amir Shamsi
  • 319
  • 3
  • 13