代码之家  ›  专栏  ›  技术社区  ›  SaidbakR

将Python字典转换为不带字符串键的JSON对象

  •  0
  • SaidbakR  · 技术社区  · 5 年前

    kaggle Notebook kernel - 请结账

    我使用了以下代码:

    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'},...
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   Johan Schiff    5 年前

    格式良好的JSON应该使用字符串作为键,如下所示:

    事实上,您可以在js中使用{country:“country”}声明对象,这只是一种方便快捷的方式。用引号声明同样有效,有时甚至更好(您的密钥可以使用+/-和其他字符)。