|Python| cvs json

From .csv to .json
The format of data.csv:
country, location, school_name,url

I save every row as a dictionary “row = {}”
And “data” is the list of dictionaries.

import json
import csv

data = []
with open('data.csv', newline='') as csvFile:
csvReader = csv.DictReader(csvFile)
for each in csvReader:
 row ={}
 row['country'] = each['country']
 row['location'] = each['location']
 row['name'] = each['name']
 row['url'] = each['url']

jsonFilePath = 'saved.json'
with open(jsonFilePath, 'w') as write_file:
 write_file.write(json.dumps(data, indent = 4))

From .json to data structures

The format of saved.json:
// saved.json
  ”country”: “US”,
  ”location”: “TX”,
  ”school”: “University of Texas”,
  ”url”: “https://ece.utdallas.edu/”
  ”country”: “US”,
  ”location”: “CA”,
  ”name”: “University of California”,
  ”url”: “”

I put the array as dictionary.
Hence, I pull every array of json_array, then put into tmp_dict.

import json

with open('saved.json', 'r') as input_file:
    json_array = json.load(input_file)

store_dict_as_list = []
for item in json_array:
    tmp_dict = {}
    tmp_dict['country'] = item['country']
    tmp_dict['location'] = item['location']
    tmp_dict['name'] = item['name']
    tmp_dict['url'] = item['url']

Comments are closed.


Up ↑