Here's the data that I have:
['{"end_date":"2021-07-15 09:00:00","number":"CHG81923","requested_by":"Dan","cmdb_ci":"LR Resort"}','{"end_date":"2021-07-15 06:00:00","number":"CHG13146","requested_by":"Tery","cmdb_ci":"My Service"}']
Actual result needs to be in tabular form by formatting the above content. There is limitation in using Pandas and ast
module.
How can I print the result like this?
End Date Number Requester CMDB
2021-07-15 09:00:00 CHG81923 Dan LR Resort
2021-07-15 06:00:00 CHG13146 Tery My Service
try pandas
for simplicity
import json
import pandas as pd
data = ['{"end_date":"2021-07-15 09:00:00","number":"CHG81923","requested_by":"Dan","cmdb_ci":"LR Resort"}','{"end_date":"2021-07-15 06:00:00","number":"CHG13146","requested_by":"Tery","cmdb_ci":"My Service"}']
df = pd.DataFrame.from_dict(map(json.loads, data))
df.rename(columns={
'end_date': 'End Date',
'number': 'Number',
'requested_by': 'Requester',
'cmdb_ci': 'CMDB'
}, inplace=True)
print(df)
End Date Number Requester CMDB
0 2021-07-15 09:00:00 CHG81923 Dan LR Resort
1 2021-07-15 06:00:00 CHG13146 Tery My Service
To save as csv use
df.to_csv('file.csv')
import json
d = ['{"end_date":"2021-07-15 09:00:00","number":"CHG81923","requested_by":"Dan","cmdb_ci":"LR Resort"}','{"end_date":"2021-07-15 06:00:00","number":"CHG13146","requested_by":"Tery","cmdb_ci":"My Service"}']
data = [json.loads(i) for i in d]
headers = ['End Date', 'Number', 'Requester', 'CMDB']
max_column_heights = [max(map(len, i))+5 for i in zip(*[i.values() for i in data], headers)] #+5 for extra space
for each_row in [headers] + [i.values() for i in data]:
for column, i in enumerate(each_row):
print(i.ljust(max_column_heights[column]), end='')
print()
# End Date Number Requester CMDB
# 2021-07-15 09:00:00 CHG81923 Dan LR Resort
# 2021-07-15 06:00:00 CHG13146 Tery My Service
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.