Reputation: 4859
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.
Upvotes: 0
Views: 117
Reputation: 1104
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, e.g. '\"order\"'
Upvotes: 1
Reputation: 280181
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
Upvotes: 5