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

时间:2018-08-28 04:30:07

标签: python json python-3.x

我想创建一个像这样的json文件:

Type library exporter encountered an error while processing 'CopyAsHtml.CopyAsHtmlPackage, CopyAsHtml'. Error: Type library exporter encountered an error while processing 'Microsoft.VisualStudio.Shell.Interop.SVsSolutionObject, Microsoft.VisualStudio.Shell.Interop'. Error: Type 'SVsSolutionObject' and type 'SVsSolution' both have the same UUID.

我正在只包含Unix Timestamp的列并将它们分组。

{"946705035":4,"946706692":4 ...}

转换为字典

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

结果 enter image description here 这是我期望的数据结构

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)

3 个答案:

答案 0 :(得分:7)

您要两次转储JSON,这会使引号在第二次转储中转义。 (在第一个json.dumps之后,结果只是一个字符串,因此您只是在转储一个字符串而不是一个dict)

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)

答案 1 :(得分:0)

解决上述问题的最简单方法是与json.dumps()json.loads()一起玩。

import json
result = json.dumps(result)

with open('result.json', 'w') as fp:
    json.loads(result, fp)

答案 2 :(得分: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)