首页 > 解决方案 > 在python中将表数据框隐藏到json api请求

问题描述

我使用 pandas 在网站上抓取表格并获取数据框。我只需要来自具有长标题的数据框中的一列数据。我需要将这些标题插入到如下所示的 json api 请求中:

payload = "{\n    \"campaign_id\": 1,\n    \"identifiers\": [\n        {\n            \"identifier\": \"scraped titles\",\n            \"type\": \"keyword\"\n        }\n    ]\n}"

正如你所看到的,title 是一个嵌套的字典对。(我认为这就是你所说的)。因此,我需要像上面那样迭代每个标题:{"identifier":"Scraped Title", "type":"keyword"}对于整个表。

所以我拥有的是数据表:标识符 1 2 3 4 n

我需要的是

{'identifier': '1', 'type': 'keyword'}, {'identifier': '2', 'type': 'keyword'}, {'identifier': '3', 'type': '关键字'},{'标识符':'4','类型':'关键字'},{'标识符':'n','类型':'关键字'}

谢谢!

标签: pythonjsonpandas

解决方案


尝试这个,

items = [1, 2, 3, 4, 5...]

# list comprehension..
print([{'identifier': item, 'type': 'keyword'} for item in items])

输出

[{'identifier': 1, 'type': 'keyword'}, {'identifier': 2, 'type': 'keyword'}..]

推荐阅读