1

I am getting this error while trying to clean a json data, save it into another json and finally converting it into a csv file: for data1 in n: TypeError: 'int' object is not iterable

This is my code:

import json
import csv

with open('leap_data.json') as f:
    data = json.load(f)
#print(data)
cnt=0
final_list={}

for k,v in data.items():
    for m,n in v.items():
        #print n
        cnt=cnt+1
        #print cnt
        if cnt==6:
            #print n
            for data1 in n:
                for a,b in data1.items():
                    final_list[a]=b    
                with open('output4.json', 'a') as outfile:  
                    json.dump(final_list,outfile)

            my_list = "["+open('output4.json').read().replace("}{","},{")+"]"
            data_1 = json.loads(my_list)
            print(data_1)


with open(r'samp.csv', 'w+') as csvfile:
  output = csv.writer(csvfile)
  output.writerow(data_1[0].keys())
  for row in data_1:
        output.writerow(row.values())

Please suggest how to get rid of this

Souvik Pal
  • 21
  • 3

1 Answers1

2

Dictionary's .items() doesnot return lists in Python3. Please refer this question

Sample Python2 code

for k, v in features.items():

Equivalent Python3 code

for k, v in list(features.items()):

Your code in Python3 (generated in pythonconverter)

import json
import csv

with open('leap_data.json') as f:
    data = json.load(f)
#print(data)
cnt=0
final_list={}

for k,v in list(data.items()):
    for m,n in list(v.items()):
        #print n
        cnt=cnt+1
        #print cnt
        if cnt==6:
            #print n
            for data1 in n:
                for a,b in list(data1.items()):
                    final_list[a]=b    
                with open('output4.json', 'a') as outfile:  
                    json.dump(final_list,outfile)

            my_list = "["+open('output4.json').read().replace("}{","},{")+"]"
            data_1 = json.loads(my_list)
            print(data_1)


with open(r'samp.csv', 'w+') as csvfile:
  output = csv.writer(csvfile)
  output.writerow(list(data_1[0].keys()))
  for row in data_1:
        output.writerow(list(row.values()))

Hope this works!

Sreeragh A R
  • 2,871
  • 3
  • 27
  • 54