Skip to content

Instantly share code, notes, and snippets.

@venkatsgithub1
Last active June 4, 2019 01:16
Show Gist options
  • Save venkatsgithub1/94813dfc57cac8123a42286467af129b to your computer and use it in GitHub Desktop.
Save venkatsgithub1/94813dfc57cac8123a42286467af129b to your computer and use it in GitHub Desktop.
Loading a json file and writing to csv in python 2.7.15
import json
import csv
with open('./test.json', 'r') as f1:
# read data as string.
data_json = f1.read()
# loads method converts string data into dictionary.
dict1=json.loads(data_json)
print dict1
# accessing data
# access td first, from td, access a.
print dict1['td']['a']
# access arr first, from arr access 0th index, which has a2 data, once at 0th index, access a2 data.
print dict1['arr'][0]['a2']
# writing to csv
with open('./output.csv', 'w') as f2:
csv_writer = csv.writer(f2)
csv_writer.writerow(['A','B'])
csv_writer.writerow([dict1['td']['a'], dict1['arr'][0]['a2']])
import json
import csv
with open('./test_2.json', 'r') as f1:
# read data as string.
data_json = f1.read()
# loads method converts string data into dictionary.
list1=json.loads(data_json)
print list1
# accessing data
for row in list1:
print(row)
# access row by index
print list1[0]
# # writing to csv
with open('./output2.csv', 'w') as f2:
csv_writer = csv.writer(f2)
csv_writer.writerow(['A','B'])
for row in list1:
csv_writer.writerow([row['td']['a'], row['arr'][0]['a2']])
A B
Apple Azerbaijan
A B
Apple Azerbaijan
Apricot Argentina
{
"td":{
"a":"Apple",
"b":"Bat"
},
"cd":{
"a1":"Al",
"b1":"Bob"
},
"arr":[
{
"a2":"Azerbaijan"
},
{
"b2":"Baku"
}
]
}
[
{
"td":{
"a":"Apple",
"b":"Bat"
},
"cd":{
"a1":"Al",
"b1":"Bob"
},
"arr":[
{
"a2":"Azerbaijan"
},
{
"b2":"Baku"
}
]
},
{
"td":{
"a":"Apricot",
"b":"Bus"
},
"cd":{
"a1":"Aaron",
"b1":"Brian"
},
"arr":[
{
"a2":"Argentina"
},
{
"b2":"Buenos Aires"
}
]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment