将字符串格式的 url 的 DataFrame 正确转换为 JSON

2024-01-20

我有一个包含 2 列的数据框,其中一列由 URL 组成。

示例代码:

df = pd.DataFrame(columns=('name', 'image'))
df = df.append({'name': 'sample_name', 'image': 'https://images.pexels.com/photos/736230/pexels-photo-736230.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'}, ignore_index=True)
df = df.append({'name': 'sample_name2', 'image': 'https://cdn.theatlantic.com/assets/media/img/mt/2017/10/Pict1_Ursinia_calendulifolia/lead_720_405.jpg?mod=1533691909'}, ignore_index=True)

我想直接将此数据帧转换为 JSON。我用过to_json()DataFrame 的方法进行转换,但是当我这样做时,它会弄乱数据框中的 url。

转换为 JSON:

json = df.to_json(orient='records')

当我打印它时,转换会将“\”字符插入到网址中每个“/”字符的开头。

print(json)

Result:

[{"name":"sample_name","image":"https:\/\/images.pexels.com\/photos\/736230\/pexels-photo-736230.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"},{"na
me":"sample_name2","image":"https:\/\/cdn.theatlantic.com\/assets\/media\/img\/mt\/2017\/10\/Pict1_Ursinia_calendulifolia\/lead_720_405.jpg?mod=15
33691909"}]

我希望 json 看起来像(网址中没有额外的“\”):

[{"name":"sample_name","image":"https://images.pexels.com/photos/736230/pexels-photo-736230.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"},{"na
    me":"sample_name2","image":"https://cdn.theatlantic.com/assets/media/img/mt/2017/10/Pict1_Ursinia_calendulifolia/lead_720_405.jpg?mod=15
    33691909"}]

我检查了文档to_json()以及其他问题,但找不到解决问题的答案。我怎样才能将我的 url 字符串转换为 json,因为它们在数据框中?


Pandas uses ujson [PiPy] https://pypi.org/project/ujson/ internally to encode the data to a JSON blob. ujson by default escapes slashes with the escape_forward_slashes https://pypi.org/project/ujson/#escape-forward-slashes option.

你可以只json.dumps(…)将数据帧转换为字典的结果.to_dict:

>>> import json
>>> print(json.dumps(df.to_dict('records')))
[{"name": "sample_name", "image": "https://images.pexels.com/photos/736230/pexels-photo-736230.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"}, {"name": "sample_name2", "image": "https://cdn.theatlantic.com/assets/media/img/mt/2017/10/Pict1_Ursinia_calendulifolia/lead_720_405.jpg?mod=1533691909"}]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将字符串格式的 url 的 DataFrame 正确转换为 JSON 的相关文章

随机推荐