gpt4 book ai didi

python - 在 python 中使用\n 分隔的 JSON 发布请求

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:02 25 4
gpt4 key购买 nike

我正在尝试使用来自 Elasticsearch 的批量 API,我看到这可以使用以下特殊请求来完成,因为作为“数据”给出的不是正确的 JSON,而是使用\n 作为分隔符。

curl -XPOST 'localhost:9200/_bulk?pretty' -H 'Content-Type: application/json' -d '
{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }
{ "field1" : "value1" }
{ "delete" : { "_index" : "test", "_type" : "type1", "_id" : "2" } }
{ "create" : { "_index" : "test", "_type" : "type1", "_id" : "3" } }
{ "field1" : "value3" }
{ "update" : {"_id" : "1", "_type" : "type1", "_index" : "test"} }
{ "doc" : {"field2" : "value2"} }
'

我的问题是如何在 python 中执行此类请求? ElasticSearch 的作者建议不要漂亮地打印 JSON 但我不确定它是什么意思(参见 https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html )

我知道这是一个有效的 python 请求

import requests
import json

data = json.dumps({"field":"value"})

r = requests.post("localhost:9200/_bulk?pretty", data=data)

但是如果 JSON 是\n 分隔的,我该怎么办?

最佳答案

这实际上是一组单独的 JSON 文档,用换行符连接在一起。所以你可以这样做:

data = [
{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } },
{ "field1" : "value1" },
{ "delete" : { "_index" : "test", "_type" : "type1", "_id" : "2" }, },
{ "create" : { "_index" : "test", "_type" : "type1", "_id" : "3" }, },
{ "field1" : "value3" },
{ "update" : {"_id" : "1", "_type" : "type1", "_index" : "test"} },
{ "doc" : {"field2" : "value2"} }
]

data_to_post = '\n'.join(json.dumps(d) for d in data)
r = requests.post("localhost:9200/_bulk?pretty", data=data_to_post)

但是,正如评论中所指出的,Elasticsearch Python 客户端可能更有用。

关于python - 在 python 中使用\n 分隔的 JSON 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45143005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com