Python读取ElasticSearch查询JSON文件报错如何修复?
问题说明
- 编写了一份
JSON格式的ElasticSearch查询配置文件,查询语句本身在ElasticSearch中可以正常执行返回结果 - 初步校验JSON格式显示合法,但使用Python标准库
json模块读取文件时抛出解析错误
原始JSON文件内容
{ "function_score": { "query": { "bool": { "should": [ { "query_string": { "default_field": "headline", "query": "engineer" } }, { "match_all": {} } ] } }, "functions": [ { "script_score": { "script": { "params": { "queryVector": [1,2,5], "max_score": "max_score" }, "source": "if (_score>0 && params.max_score>0){return doc['embedding_headline'].size() == 0 ? 0 : Math.min(Math.max(_score/params.max_score,cosineSimilarity(params.queryVector, 'embedding_headline')),1) + 1.0} else { return doc['embedding_headline'].size() == 0 ? 0 : cosineSimilarity(params.queryVector, 'embedding_headline') + 1.0}", "lang": "painless" } } } ], "score_mode": "max", "boost_mode": "replace", } }
读取代码
import json file_path = 'queries.json' with open(file_path) as f: data = json.load(f) print(data)
报错信息
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 34 column 5 (char 1012)
错误原因
JSON语法不合法:"boost_mode": "replace"这一行末尾多了一个多余的尾逗号。
部分宽松的解析器(包括ElasticSearch自带的解析逻辑、部分网页JSON校验工具)会兼容这种尾逗号写法,但Python标准库json模块严格遵循官方JSON规范,不允许对象的最后一个属性后出现多余逗号,因此触发解析错误。
修复方案
删除"boost_mode": "replace"行尾的多余逗号即可,修复后的合法JSON内容如下:
{ "function_score": { "query": { "bool": { "should": [ { "query_string": { "default_field": "headline", "query": "engineer" } }, { "match_all": {} } ] } }, "functions": [ { "script_score": { "script": { "params": { "queryVector": [1,2,5], "max_score": "max_score" }, "source": "if (_score>0 && params.max_score>0){return doc['embedding_headline'].size() == 0 ? 0 : Math.min(Math.max(_score/params.max_score,cosineSimilarity(params.queryVector, 'embedding_headline')),1) + 1.0} else { return doc['embedding_headline'].size() == 0 ? 0 : cosineSimilarity(params.queryVector, 'embedding_headline') + 1.0}", "lang": "painless" } } } ], "score_mode": "max", "boost_mode": "replace" } }
替换文件内容后重新运行读取代码即可正常解析。
内容的提问来源于stack exchange,提问作者ivan100096
相关产品推荐
相关产品推荐

