本文介绍了如何使Python中有效的JSON格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让JSON从弹性搜索中获取查询。我使用这个代码构建查询:

  search_doc = {} 
search_doc.update({sort :{{re_max:{order:desc}}]})
search_doc.update({from:0})
search_doc.update({size 100)
search_doc.update({filter:{and:[{term:{country_id:10}},{range:{pub_date gte:2014-06-07T00:00:00.0,lte:2014-06-07T23:59:59.0}}}}}}
pre>

如您所见,我在所有字符串中使用了双引号,但查看了打印结果:

  {'sort':[{'re_max':{'order':'desc'}}],'filter':{'和':[{'term' 'country_id':'10'}},{'range':{'pub_date':{'gte':'2014-06-07T00:00:00.0','lte':'2014-06-07T23:59: 59.0'}}}},'from':0,'size':100} 

单引号在JSON格式无效或至少弹性搜索将不接受。有没有办法使我的字符串有效的JSON格式?我认为这不是用双引号取代单引号的好方法。请帮助我,如果有办法。

解决方案

不要打印 dict。使用模块:

  import json 
json_string = json.dumps(search_doc)

该模块还允许您执行相反的转换,将JSON转换为Python数据结构:

  reparsed_dict = json.loads(json_string)
#reparsed_dict == search_doc


I want to make JSON to get queries from elastic search. I'm usgin this code to build the query:

search_doc = {}
        search_doc.update({"sort": [{"re_max": {"order": "desc"}}]})
        search_doc.update({"from": 0})
        search_doc.update({"size": 100})
        search_doc.update({"filter": {"and": [{"term": {"country_id": "10"}},{"range": {"pub_date": {"gte": "2014-06-07T00:00:00.0", "lte": "2014-06-07T23:59:59.0"}}}]}})

as you see I've used double quotation in all my strings, but look at the printed result:

{'sort': [{'re_max': {'order': 'desc'}}], 'filter': {'and': [{'term': {'country_id': '10'}}, {'range': {'pub_date': {'gte': '2014-06-07T00:00:00.0', 'lte': '2014-06-07T23:59:59.0'}}}]}, 'from': 0, 'size': 100}

All with single quotation which is invalid in JSON format or at least Elastic search will not accept it. Is there a way to make my strings in a valid JSON format? I think this is not a good way to replace single quotations with double quotations. please help me if there is a way.

解决方案

Don't print the dict. Get a valid JSON string using the json module:

import json
json_string = json.dumps(search_doc)

The module also lets you perform the opposite conversion, turning JSON into Python data structures:

reparsed_dict = json.loads(json_string)
# reparsed_dict == search_doc

这篇关于如何使Python中有效的JSON格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:46