【问题标题】:Python is returning json response in single quotes not double (Elasticsearch API)Python 在单引号中返回 json 响应而不是双引号(Elasticsearch API)
【发布时间】:2022-01-21 19:07:02
【问题描述】:

我在 python 中使用Elasticsearch 库来查询弹性搜索服务器,如下所示:

query = {
   "query":{
      "match_all":{}
   }
}
es = Elasticsearch('localhost:9200')
res = es.search(index='myindex', body=query)
with open('response.json', 'w') as out:
    out.write(res)
    # json.dump(res, out) also gives the same result

我保存到文件的输出具有格式

{ 
    'key':'value',
    'key2': {
       'key3' : 'value2'
    }
}

请注意此处的单引号。我知道我可以做一个简单的查找和替换或使用sed 将单引号更改为双引号,但是,我想知道为什么在终端使用curl 时会发生这种情况。

我希望以正确的json 格式转储输出

【问题讨论】:

    标签: python json elasticsearch response dump


    【解决方案1】:

    Python 字典对象不一定自动为 json 格式。上述问题可以通过在响应中使用json.dumps() 来解决,如下所示:

    query = {
       "query":{
          "match_all":{}
       }
    }
    es = Elasticsearch('localhost:9200')
    res = es.search(index='myindex', body=query)
    with open('response.json', 'w') as out:
        out.write(json.dumps(res))
    

    这会将res 转换为json 格式,如下所示:

    { 
        "key":"value",
        "key2": {
           "key3" : "value2"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-18
      • 2015-12-12
      • 2017-07-09
      • 1970-01-01
      • 2023-03-13
      • 2011-05-08
      相关资源
      最近更新 更多