Home > front end >  read in sequence different json file
read in sequence different json file

Time:12-06

I have different JSON files in my local directory and I read all of them with this code

path_to_json = 'C:/Users/../Desktop/NewData'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
def func(s):
    try:
        return eval(s)
    except:
        return dict()
list_of_df=[]
for i in range(len(json_files)):
    try:
        file_name = json_files[i]
        df = pd.read_json(file_name, lines=True)
        df= df[['something']]
        df = df['something'].apply(func)
        df=pd.json_normalize(df)
        df=pd.DataFrame(df[["something", "something1"]])
        df['Index'] = 'weather5'   str(6 i)
    except:
        pass
    list_of_df.append(df)
df=pd.concat(list_of_df)
df = df[['Index','something', 'something1']]
df.head() 

The name of the JSON files that I read are weather56, weather57, weather58, weather59, weather60, weather61

I am using this line df['Index'] = 'weather5' str(6 i) to read them properly and adjust them to a dataframe. However seem that I do not read them properly as now appears in the dataframe as:

Index
weather56
weather57
weather58
weather59
weather510
weather511

How to adjust this line df['Index'] = 'weather5' str(6 i) to read the JSON files with their names?

CodePudding user response:

df['Index'] = 'weather5'   str(6 i)

As i goes from 0 to 6, the corresponding values generated are going to be

weather56   // '5'   str(6   0)
weather57
weather58
weather59
weather510  // '5'   str(6   4) := '5'   '10'
weather511

If you change the line to

df['Index'] = 'weather'   str(56 i)

it should appear as -

weather56
weather57
weather58
weather59
weather60
weather61
  • Related