简体   繁体   English

将Python字典转换为没有字符串键的JSON对象

[英]Convert Python dictionary to JSON object without string key

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.我创建了一个kaggle Notebook 内核-请检查它- 使用世界数据源的国家/地区,以获得处理每个国家/地区及其各自人口的 JSON 对象列表,因为我想在 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.这里的活动代码是load_tokens()方法。 What I have ended with is an output print(data) like the following:我已经结束的是一个输出print(data) ,如下所示:

[{'country': 'Country', 'population': 'Population'}, {'country': 'Afghanistan', 'population': '31056997'}, {'country': 'Albania', 'population': '3581655'}, {'country': 'Algeria', 'population': '32930091'},...]

My problem here is the dictionary keys.我的问题是字典键。 ie 'country' and 'population' I don't want them to be strings.'country''population'我不希望它们成为字符串。 I need them to be JSON object's keys like found in JavaScript:我需要它们是 JSON 对象的键,就像在 JavaScript 中找到的一样:

[{country: 'Country', population: 'Population'},{country: 'Afghanistan', population: '31056997'},...

Well formatted JSON should use strings as keys, like this: {"country": "Country"}格式良好的 JSON 应该使用字符串作为键,像这样:{"country": "Country"}

The fact that you can declare objects using {country: "Country"} in js is just a convenience shortcut.您可以在 js 中使用 {country: "Country"} 声明对象只是一个方便的快捷方式。 Declaring with quotes works the same, or sometimes better (your key can use +/- and other chars).用引号声明的效果相同,有时更好(您的密钥可以使用 +/- 和其他字符)。

Don't convert from JSON back to python objects (using json.loads()), though.但是,不要从 JSON 转换回 python 对象(使用 json.loads())。 Python objects are not JSON objects, and even in how they are displayed there are subtle differences. Python 对象不是 JSON 对象,甚至在它们的显示方式上也存在细微的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM