I had created a kaggle Notebook kernel -Please Checkout it- with countries of the world data source, in order to obtain a list of JSON objects that handles each country and its respective population, because I want to use a textual copy of it in JavaScript.
I used the following code:
data = []
import csv
import json
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
file_name = os.path.join(dirname, filename)
print(file_name)
print('Done!')
# Any results you write to the current directory are saved as output.
# LOOK AT THE FOLLOWING Method:
def load_tokens(tokens_file):
try:
with open(tokens_file) as csvDataFile:
csvReader = csv.reader(csvDataFile)
for i,row in enumerate(csvReader):
data.insert(i,json.loads(json.dumps({'country':row[0].strip(), 'population':row[2].strip()})))
The active code here is load_tokens() method. What I have ended with is an output print(data) like the following:
[{'country': 'Country', 'population': 'Population'}, {'country': 'Afghanistan', 'population': '31056997'}, {'country': 'Albania', 'population': '3581655'}, {'country': 'Algeria', 'population': '32930091'},...]
My problem here is the dictionary keys. i.e. 'country' and 'population' I don't want them to be strings. I need them to be JSON object's keys like found in JavaScript:
[{country: 'Country', population: 'Population'},{country: 'Afghanistan', population: '31056997'},...
{country: 'Country'}is only well defined ifcountryis a defined variable (whose value is hashable). Why exactly do you think{'country': 'Country', ....}is a problem.json.loads(json.dumps(...))seems pointless to me. What are you trying to achieve by loading the JSON back into Python objects?'country'will not be accessed as a property in JavaScript. i.e.obj.countrywill not work in a loop. Yes, I try to generate JavaScript array of JSON objects.