我想创建一个这样的 json 文件:
{"946705035":4,"946706692":4 ...}
我正在使用一个仅包含 Unix 时间戳的列并将它们分组。
result = data['Last_Modified_Date_unixtimestamp_no_time'].value_counts()
In [21]: result.head()
Out[21]:
1508284800 131
1508716800 106
1508371200 101
1508457600 99
1508630400 96
Name: Last_Modified_Date_unixtimestamp_no_time, dtype: int64
转化为字典
result = result.to_dict()
result
'''
{1507161600: 1,
1507852800: 1,
1508198400: 64,
1508284800: 131,
...
1535155200: 1,
1535241600: 1}
'''
import json
result = json.dumps(result)
with open('result.json', 'w') as fp:
json.dump(result, fp, indent=4)
{"946705035":4,"946706692":4}
原文由 Papouche Guinslyzinho 发布,翻译遵循 CC BY-SA 4.0 许可协议
您转储了 JSON 两次,这导致引号在第二次转储时被转义。 (在第一个
json.dumps
结果只是一个字符串之后,所以你只是再次转储一个字符串而不是一个字典)或者删除第二个转储: