-2

I am not a python expert. I need help with the following data in the Data.txt file

Data.txt

{"ID83": {"Job1": {"Job_Num": "ABC.179", "Job_PNo": "26", "Job_SNo": "750", "Job_name": "Job1"}}} {"ID84": {"Job1": {"Job_Num": "ABC.180", "Job_PNo": "27", "Job_SNo": "850", "Job_name": "Job1a"}}} {"ID85": {"Job2": {"Job_Num": "DEF.20", "Job_PNo": "28", "Job_SNo": "950", "Job_name": "Job2"}}} {"ID86": {"Job3": {"Job_Num": "CDE.150", "Job_PNo": "29", "Job_SNo": "50", "Job_name": "Job3"}}} {"ID87": {"Job2": {"Job_Num": "XYZ.20", "Job_PNo": "30", "Job_SNo": "200", "Job_name": "Job2a"}}} {"ID83": {"Job3": {"Job_Num": "CDE.151", "Job_PNo": "30", "Job_SNo": "55", "Job_name": "Job3a"}}}

I need to convert the above to a .csv file with the following fields and following headers.

ID Job_Name Job_Num Job_PNo Job_SNo

The Job_PNo and Job_SNo are integers and the rest strings. Please help in the conversion. I tried with pandas but I did not get the answer

cs95
  • 379,657
  • 97
  • 704
  • 746
Kavita G
  • 1
  • 1
  • 2
    What have you tried so far? You need to show that you put effort in solving it. SO community won't solve solutions for you. – vishes_shell Jun 14 '17 at 07:23
  • Your data.txt isn't a valid python data. It's not a string and not a dict. Can you edit your question and add the specific nature of your data.txt ? – Chiheb Nexus Jun 14 '17 at 07:26
  • *I am not a python expert* , Even I'm not. But, I like to Google any of my issue, before posting. https://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv – Ravi Jun 14 '17 at 07:26
  • 2
    Possible duplicate of [How can I convert JSON to CSV?](https://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv) – Ravi Jun 14 '17 at 07:27

1 Answers1

1
a = [{"ID83": {"Job1": {"Job_Num": "ABC.179", "Job_PNo": "26", "Job_SNo": "750", "Job_name": "Job1"}}},
{"ID84": {"Job1": {"Job_Num": "ABC.180", "Job_PNo": "27", "Job_SNo": "850", "Job_name": "Job1a"}}},
{"ID85": {"Job2": {"Job_Num": "DEF.20", "Job_PNo": "28", "Job_SNo": "950", "Job_name": "Job2"}}},
{"ID86": {"Job3": {"Job_Num": "CDE.150", "Job_PNo": "29", "Job_SNo": "50", "Job_name": "Job3"}}},
{"ID87": {"Job2": {"Job_Num": "XYZ.20", "Job_PNo": "30", "Job_SNo": "200", "Job_name": "Job2a"}}},
{"ID83": {"Job3": {"Job_Num": "CDE.151", "Job_PNo": "30", "Job_SNo": "55", "Job_name": "Job3a"}}},
]

ret = []
for d in a:
  line = []
  for (k,v) in d.items():
    line.append(k)
    inner_dict = list(v.values())[0]
    line.append(inner_dict['Job_name'])
    line.append(inner_dict['Job_Num'])
    line.append(inner_dict['Job_PNo'])
    line.append(inner_dict['Job_SNo'])
  ret.append(line)

csvstr = '\n'.join([','.join(i) for i in ret])

with file('out.csv', 'w') as f:
    f.write(csvstr)
Ricky Han
  • 1,309
  • 1
  • 15
  • 25