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

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

可能是 使用 Python 将 JSON 数据漂亮地打印到文件中的需求 的重复问题。 - OneCricketeer
这个方案看起来合适吗?Json dumps转义正斜杠 - Matthew
我看到你正在使用pandas dataframe。在这种情况下,如果你想将你的df作为响应发送,而不是将其转换为json,请考虑将其转换为dict,然后对dict进行编码和发送json。这样做效果很好,也是标准的做法。请参考我的答案https://dev59.com/Jq3la4cB1Zd3GeqPU_fF#73448710。 - Aashish Chaubey
4个回答

19

你重复转换了 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)

有没有一种简单的方法来测试 result 的类型?这样,我们就可以写成 if type(result) is <json string>: fp.write(result) ... else: json.dump(result,fp) - blong
@blong type(result) is str,但更好的做法是跟踪您的代码并注意JSON被转储的位置。只需按照我的答案执行一次即可。 - iBug

1
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)

3
请添加一些关于如何解决问题的说明。 - Arghya Sadhu

0

首先将DataFrame转换为字典

response = df.to_dict(orient="records")

然后将响应编码为json格式

json_compatible_data = jsonable_encoder(response)

这应该很好用。


-1

解决上述问题最简单的方法是使用 json.dumps()json.loads()

import json
result = json.dumps(result)

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

是的,你可以试试。 - Rushabh Sudame
1
json.loads() 的第二个参数毫无意义 - 它只接受一个位置参数。 - iBug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接