简体   繁体   中英

How to make a valid format JSON in python?

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

The dictionaries you're using are not JSON but python internal objects. You can use json.dumps() to create proper JSON strings. The python standard is single quotes which is why you see them when you print it. If you need quotation marks inside the string itself, you can escape them using the backslash, eg '\\"order\\"'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM