Skip to main content
 首页 » 编程设计

python之如何从 JSON 文件中删除反斜杠

2025年05月04日12freeliver54

我想创建一个像这样的 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} 

请您参考如下方法:

您转储了 JSON 两次,这导致引号在第二次转储时被转义。 (在第一个 json.dumps 之后,结果只是一个字符串,所以你只是再次转储一个字符串而不是一个字典)

import json 
# result = json.dumps(result) 
 
with open('result.json', 'w') as fp: 
    json.dump(result, fp, indent=4) 

或者删除第二个转储:

import json 
result = json.dumps(result) 
 
with open('result.json', 'w') as fp: 
    # json.dump(result, fp, indent=4) 
    print(result, file=fp)