如何在python中制作有效的格式JSON?

ehs*_*adi 0 python json elasticsearch

我想让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"}}}]}})
Run Code Online (Sandbox Code Playgroud)

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

{'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}
Run Code Online (Sandbox Code Playgroud)

所有单引号都是JSON格式无效或至少是弹性搜索都不接受它.有没有办法让我的字符串以有效的JSON格式?我认为这不是用双引号替换单引号的好方法.如果有办法,请帮助我.

use*_*ica 5

不要print这个词.使用该json模块获取有效的JSON字符串:

import json
json_string = json.dumps(search_doc)
Run Code Online (Sandbox Code Playgroud)

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

reparsed_dict = json.loads(json_string)
# reparsed_dict == search_doc
Run Code Online (Sandbox Code Playgroud)