我创建了一个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'
我不希望它们是字符串。我需要它们是 JSON 对象的键,就像在 JavaScript 中找到的那样:
[{country: 'Country', population: 'Population'},{country: 'Afghanistan', population: '31056997'},...
最佳答案
格式良好的 JSON 应该使用字符串作为键,如下所示: {“国家”:“国家”}
在 js 中使用 {country: "Country"} 声明对象只是一种方便的快捷方式。使用引号声明的效果相同,有时甚至更好(您的 key 可以使用 +/- 和其他字符)。
不过,不要将 JSON 转换回 Python 对象(使用 json.loads())。 Python 对象不是 JSON 对象,甚至在显示方式上也存在细微差别。
关于javascript - 将Python字典转换为不带字符串键的JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60921330/