我已经使用世界数据源的国家/地区创建了一个kaggle Notebook kernel-请签出它-,以便获取处理每个国家及其各自人口的JSON对象列表,因为我想在JavaScript中使用它的文本副本。
我使用了以下代码:
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()})))
这里的活动代码是load_tokens()
方法。我结束的是一个输出print(data)
,如下所示:
[{'country': 'Country', 'population': 'Population'}, {'country': 'Afghanistan', 'population': '31056997'}, {'country': 'Albania', 'population': '3581655'}, {'country': 'Algeria', 'population': '32930091'},...]
我的问题是字典键。即'country'
和'population'
我不希望它们是字符串。我需要它们像在JavaScript中那样成为JSON对象的键:
[{country: 'Country', population: 'Population'},{country: 'Afghanistan', population: '31056997'},...
答案 0 :(得分:1)
格式良好的JSON应该使用字符串作为键,如下所示: {“国家”:“国家”}
您可以在js中使用{country:“ Country”}声明对象的事实只是一个便捷快捷方式。用引号声明可以相同或有时更好(您的键可以使用+/-和其他字符)。
但是,不要从JSON转换回python对象(使用json.loads())。 Python对象不是JSON对象,即使在显示方式上也存在细微差别。