如何将CSV转JSON时的索引保持为整数类型?
问题:CSV转JSON时整数索引变为字符串的解决方法
场景与问题
我有一个包含法语和英语单词的CSV文件:
French,English partie,part histoire,history chercher,search seulement,only police,police
尝试将其转换为JSON时,希望索引为整数类型,但生成的JSON中索引自动变成了字符串,用int()转换也无法解决。
我的代码:
import json import pandas data = pandas.read_csv("data/french_words.csv") words = {int(index): { "French": row.French, "English": row.English, "known": None } for index, row in data.iterrows() } data.update(words) with open("words.json", mode="w") as words_file: json.dump(words, words_file, indent=4) print(words)
控制台输出(Python字典的键为整数):
{ 0: {'French': 'partie', 'English': 'part', 'known': None}, 1: {'French': 'histoire', 'English': 'history', 'known': None}, 2: {'French': 'chercher', 'English': 'search', 'known': None}, 3: {'French': 'seulement', 'English': 'only', 'known': None}, 4: {'French': 'police', 'English': 'police', 'known': None}, 5: {'French': 'pensais', 'English': 'thought', 'known': None}, }
生成的JSON文件输出(键变为字符串):
{ "0": { "French": "partie", "English": "part", "known": null }, "1": { "French": "histoire", "English": "history", "known": null }, "2": { "French": "chercher", "English": "search", "known": null }, "3": { "French": "seulement", "English": "only", "known": null }, "4": { "French": "police", "English": "police", "known": null }, "5": { "French": "pensais", "English": "thought", "known": null }, }
原因
JSON语法明确规定,对象的键必须是字符串类型。即便Python字典中使用整数作为键,json.dump()在序列化时也会自动将整数键转换为字符串,这是JSON的固有特性,无法直接改变。
解决方案
方案1:改用数组(列表)结构(推荐)
JSON数组的索引天然是整数,无需显式定义键,完美匹配需求。修改后的代码:
import json import pandas data = pandas.read_csv("data/french_words.csv") # 将每行数据转为字典,组成列表 words_list = [ { "French": row.French, "English": row.English, "known": None } for _, row in data.iterrows() ] with open("words.json", mode="w") as words_file: json.dump(words_list, words_file, indent=4)
生成的JSON内容(数组结构,索引为整数):
[ { "French": "partie", "English": "part", "known": null }, { "French": "histoire", "English": "history", "known": null }, { "French": "chercher", "English": "search", "known": null }, { "French": "seulement", "English": "only", "known": null }, { "French": "police", "English": "police", "known": null }, { "French": "pensais", "English": "thought", "known": null } ]
方案2:保留键值对结构,读取时转换键类型
如果必须保留键值对结构,只能接受JSON中的字符串键,后续读取JSON时再将键转换为整数:
# 读取JSON时转换键为整数 with open("words.json", mode="r") as words_file: json_data = json.load(words_file) words_dict = {int(key): value for key, value in json_data.items()}
内容的提问来源于stack exchange,提问作者Kbk12
相关产品推荐
相关产品推荐

