如何在python中编写json文件而不使用转储

2024-07-07 06:02:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下来自MongoDB的bson数据。我必须将代码转换成有效的json来创建PySpark数据帧。你知道吗

"\"{u'_raja': ObjectId('XXXXXX'),\\n u'ram': datetime.datetime(XXx,xx14, xx, xx, xxx),\\n u'createUserId': u'praja-policy',\\n u'raja': u'I5',\\n u'udatedTime': datetime.datetime(XXx, xx, xx, xx, xx, xx, xxxx),\\n u'lastupdatedid': u'raja_id',\\n u'plt': u'123r32'}\""

我编写了以下代码。你知道吗

from bson import json_util
with open("/XXXXX6/bi/XXXXX/XXXXX3/v0/test/bson.json", "rb") as f:
bson = f.read()
data= bson.replace('u\'','') – removal of Unicode 
data1 = data.replace('\n','') – removal of \n
json.dump(json_util.dumps(data), open("bson1.json", "w"))

使用json.dump文件提供了有效的json,但格式为“\”。你知道吗

如何提取unicode中的值?所以,我可以用板条箱装一个PySpark数据帧。你知道吗


Tags: of数据代码jsondatadatetimeutilopen
1条回答
网友
1楼 · 发布于 2024-07-07 06:02:30

在中使用确保\u ascii=Falsejson.dumps文件地址:

bson = f.read()
json.dumps(bson, ensure_ascii=False).encode('utf8')

这将避免unicode输出。encode函数可用于编码到所需的格式。大多数情况下,使用“utf8”可以确保安全

相关问题 更多 >