I'm struggling to bring my array to the right format for the JSON file! Might be an easy question for people with knowledge. I grep the data from different CSV files in the format:
[['Dec', '196610'], ['Oct', '196699'], ['Sep', '131073'], ['Jul', '122050']]
I need to bring it in the format:
{
"Year_2021": [
{
"Dec": "196610",
"oct": "196699",
"Sep": "131073",
"Jul": "122050"
}
]
}
i have tried different possibilities and got the craziest constellations, just not the right one.
My current code:
import csv
import datetime
import time
import os.path
import json
from collections import defaultdict
sys_time = datetime.datetime.now()
format_sys_time = sys_time.strftime('[%Y-%m-%d] %H:%M:%S') # Other Datetime Format
act_month = int(sys_time.strftime('%m'))
#print act_month
output_json_file = "/var/www/json/EXP_MONTHLY_POWER_" sys_time.strftime('%Y') ".json"
start_time = time.time() # measure how long a programm run takes
columns = defaultdict(list) # each value in each column is appended to a list
# Help function to build dword
def word_to_dword(val_1, val_2):
result = val_1
result |= val_2 << 16
return result
# Calculate past days of the current month
dates = []
for act_month in range(act_month 1, 1, -1):
act_month -= 1
if act_month <=9:
INPUTFILE= "/var/www/csv/EXP_POWER_" sys_time.strftime('%Y-0') str(act_month) ".csv"
else:
INPUTFILE= "/var/www/csv/EXP_POWER_" sys_time.strftime('%Y-') str(act_month) ".csv"
dates.append(INPUTFILE)
#print(dates)
outputfields = [];
#Delete old file to avoid double entrys
if os.path.exists(output_json_file):
os.remove(output_json_file)
for dayfile in dates:
if os.path.exists(dayfile):
with open(dayfile) as csvdatei:
mvg_reader = csv.DictReader(csvdatei , delimiter=';') # read rows into a dictionary format
for row in mvg_reader: # read a row as {column1: value1, column2: value2,...}
for (fieldname, value) in row.items(): # go over each column name and value
columns[fieldname].append(value) # append the value into the appropriate list
# based on column name
outfields1=[]
for value in columns['Power_Value(kwh)']:
# print(int(value))
outfields1.append(int(value))
# Build Power Value from last values of list
if (len(outfields1) != 0):
DL_Actual_Power_Value = outfields1[-1]
else:
print("Keine Daten gefunden!")
compString = ""
compString = dayfile[28:30] # Build compString from Filename
switcher = {
"01": "Jan",
"02": "Feb",
"03": "Mar",
"04": "Apr",
"05": "May",
"06": "Jun",
"07": "Jul",
"08": "Aug",
"09": "Sep",
"10": "Oct",
"11": "Nov",
"12": "Dec"
}
outputfields.append([switcher.get(compString, "Invalid month"), str(DL_Actual_Power_Value)] )
print(outputfields)
export_json_main = {}
export_json_main.clear()
export_KEY = 'Year_' sys_time.strftime('%Y') # Name des Keys festlegen
export_json_main[export_KEY] = []
export_json_main[export_KEY].append( outputfields )
#jsonStr = json.dumps(outputfields)
#print(jsonStr)
#for keys in (outputfields):
# print(keys[0])
#export_json_main[export_KEY].append({
# json.dumps(outputfields)
#})
with open(output_json_file, 'w') as outfile:
json.dump(export_json_main, outfile, indent=4)
This brings me the following output:
{
"Year_2021": [
[
[
"Dec",
"196610"
],
[
"Oct",
"196699"
],
[
"Sep",
"131073"
],
[
"Jul",
"122050"
]
]
]
}
CodePudding user response:
not sure what your code does. However you mean something like this
arr = [['Dec', '196610'], ['Oct', '196699'], ['Sep', '131073'], ['Jul', '122050']]
d = {}
for a in arr:
d[a[0]] = a[1]
result = { "Year_2021": d }
?