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

新手上路,请多包涵

我想创建一个这样的 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 许可协议

阅读 1.3k
2 个回答

您转储了 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)

原文由 iBug 发布,翻译遵循 CC BY-SA 4.0 许可协议

data_json=df.to_json(orient='records')
parsed=json.loads(data_json)

with open('my_data.json', 'w') as f:
    json.dump(parsed, f, indent=4)

原文由 clemiblac 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题