There're lots of questions regarding JSON to CSV Conversion in Python , but unfortunately couldn't solve my problem.
I've this simple simple JSON Data which is in a file and looks like this after loading.
Raw data in single line [I've structured this to understand better]:
{
"t_id":"80740185.1558980000000.120184.121164",
"s_id":"80740185",
"pt_slot":"null:null",
"ch_id":1,"o_id":121164,"c_id":120184,
"msg_type":1,
"amd":"{
\"msg\":\" some Bengali text\",
\"mask\":\"1GB_OFFER\",
\"ec\":\"1\",
\"time-out\":\"0\",
\"validity\":\"30052019 000000\"
}",
"time":1558960217731,
"dlr":"1",
"msisdn":"xxxxx",
"entity":1
}
**After loading to JSON formated data looks like below **
{
u't_id': u'80740185.1558980000000.120184.121164',
u'c_id': 120184,
u'msg_type': 1,
u'dlr': u'1',
u'msisdn': u'xxxxxxxx',
u'amd': u'{
"msg":" \u0986\u099c \u09b0\u09be\u09a4 \u09e7\u09e8\u099f\u09be\u09b0 \u09ae\u09a7\u09cd\u09af\u09c7 *21291*609# \u09a1\u09be\u09df\u09be\u09b2\u09c7 \u0995\u09bf\u09a8\u09c1\u09a8 \u09e7\u099c\u09bf\u09ac\u09bf \u09ef\u099f\u09be\u0995\u09be\u09a4\u09c7 (\u09e9\u09a6\u09bf\u09a8)",
"mask":"1GB_OFFER",
"ec":"1",
"time-out":"0",
"validity":"30052019 000000"
}',
u'entity': 1,
u's_id': u'80740185',
u'ch_id': 1,
u'time': 1558960217731,
u'pt_slot': u'null:null',
u'o_id': 121164
}
I've above very simple JSON Data which I'm trying to convert to CSV data. But getting below error.
Here is my code
#!/usr/bin/python
import json
import csv
def write_sms_dat_to_csv_file():
f = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
with open('test.dat') as fh:
data = json.load(fh)
for dt in data:
f.writerow([dt['c_id'],dt['msisdn'],dt["amd"]["mask"]])
if __name__=="__main__":
write_sms_dat_to_csv_file()
Error Message
Traceback (most recent call last):
File "./sms_data_read.py", line 16, in <module>
write_sms_dat_to_csv_file()
File "./sms_data_read.py", line 13, in write_sms_dat_to_csv_file
f.writerow([dt['c_id'],dt['msisdn'],dt['amd']['mask']])
TypeError: string indices must be integers
Removing for loops with below statement gives same error:
f.writerow([data['c_id'],data['msisdn'],data['amd']["mask"]])
test.data single json record? i.e. a single dictionary? Because if so the issue is thatfor dt in dataiterates over the keys in that dict, and the string keys are only indexed by intsamdhas ended up as a stringamdis holding a string, and you're trying to index that long string by["mask"]import astand thenf.writerow([dt['c_id'],dt['msisdn'],ast.literal_eval(dt['amd'])['mask']])work?for dt in data:just dodata["c_id"]directly