如何删除单引号,并在转换为to_json后将括号添加到pandas数据框中?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何删除单引号,并在转换为to_json后将括号添加到pandas数据框中?相关的知识,希望对你有一定的参考价值。

我已成功将pandas数据帧转换为json字符串,同时在开头添加字符串'import_data',如下所示:

a = {"import_data" : df.to_json(orient='records')}

返回:

{'import_data': '[{"\ufeffemail_addresses":"test@test.com","first_name":"test","last_name":"test","lists":1234567890},{"\ufeffemail_addresses":"Jane@Doe.com","first_name":"Jane","last_name":"Doe","lists":1234567890},{"\ufeffemail_addresses":"Pradeep@Patel.com","first_name":"Pradeep","last_name":"Patel","lists":1234567890}]'}

但是pandas 'to_json',并没有完全转换我需要传递给API的数据帧。

字符串需要,必须如下所示:

update_contact = '{"import_data": [{"email_addresses": ["test@test.com"],"first_name": "test","last_name": "test"},{"email_addresses": ["Jane@Doe.com"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["Pradeep@Patel.com"],"first_name": "Pradeep","last_name": "Patel"}],"lists": ["1234567890"]}'

to_json在第一个括号周围添加单引号,由于某种原因添加反斜杠,字母'u'和字符串\ufeffat email_address的开头。不知道如何放弃所有这些。

编辑:

这就是我只能将数据传递到API的方法:

headers = {

        'Authorization': 'Bearer x',
        'X-Originating-Ip': 'x',
        'Content-Type': 'application/json',

        }


update_contact = '{"import_data": [{"email_addresses": ["test@test.com"],"first_name": "test","last_name": "test"},{"email_addresses": ["Jane@Doe.com"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["Pradeep@Patel.com"],"first_name": "Pradeep","last_name": "Patel"}],"lists": ["1072830671"]}'

r_3 = requests.post('urlapi_key=x', headers=headers ,data = update_contact)
答案

请尝试以下代码。

update_contact = '{"import_data": [{"email_addresses": ["test@test.com"],"first_name": "test","last_name": "test"},{"email_addresses": ["Jane@Doe.com"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["Pradeep@Patel.com"],"first_name": "Pradeep","last_name": "Patel"}],"lists": ["1234567890"]}'

我们可以在双引号qazxsw poi之前使用backslash来打印它像这样"

以上是关于如何删除单引号,并在转换为to_json后将括号添加到pandas数据框中?的主要内容,如果未能解决你的问题,请参考以下文章

如何将包含单引号和双引号值的 Python 列表转换为所有双引号值

如何从 JSON 字符串中删除括号和引号

js-替换“单引号”“双引号”“尖括号”

熊猫在 to_json 时删除空值

如何以编程方式绘制边框并在 UIImageview 周围的文字后将其删除?

如何在python中将单引号字符串转换为数字[重复]