为什么json.dumps()没有返回预期的格式?
我有一个函数返回一个json
格式化为dict
。我正在使用json.dumps()
存储到一个对象中,我稍后在代码中打印该对象。我得到的退款不是我期望的典型格式json
。为什么json.dumps()没有返回预期的格式?
相关的代码片段:
rasa_decoded_output = interpreter.parse(u"{}".format(textobject.body))
rasa_json_formatted_output = json.dumps(rasa_decoded_output)
打印rasa_json_formatted_output
结果在这个(例子):
("text": "This is a test", "entities": < >, "intent_ranking": < ("confidence": 0.71653000212560282, "name": "st_testing"), ("confidence": 0.05410130707298815, "name": "exists_item"), ("confidence": 0.024777391815713805, "name": "concierge_contact_request"), ("confidence": 0.020174561099034895, "name": "exists_sauna"), ("confidence": 0.018203983982849743, "name": "issue_bugs"), ("confidence": 0.017985724341235722, "name": "exists_driver"), ("confidence": 0.01687271448223236, "name": "request_power_adapter - custom"), ("confidence": 0.016857156745106013, "name": "request_newroom"), ("confidence": 0.015943797930370658, "name": "presto_cost"), ("confidence": 0.015567442054810358, "name": "exists_spa") >, "intent": ("confidence": 0.07653000212560282, "name": "st_testing"))
什么做错了吗?应该调整什么来让json以其典型格式返回,以便我可以解析并提取所需的属性。
此外,如果我只是打印rasa_decoded_output
它与打印rasa_json_formatted_output
一样,这表明json.dumps()
没有任何效果。
使用json.loads()
上rasa_decoded_output
导致错误TypeError: the JSON object must be str, not 'dict'
的问题可能是rasa_decoded_output
可能无法解码JSON对象尚未。你可能需要先使用json.loads,一旦你这样做了,你可以使用json.dumps
感谢您的评论。它已经是一个解码的json对象字典,使用json.loads()导致错误“TypeError:JSON对象必须是str,而不是'dict'”。 – hackerman
这有点奇怪,因为json.dumps是为了给你返回一个字符串。例如json.dumps(dict(one = 1,two = 2))返回“{”one“:1,”two“:2}' – pragMATHiC
当你输入(rasa_decoded_output)时,你会得到什么? – pragMATHiC
“解释器”究竟是什么?你是如何初始化它的? – DyZ
@DYZ解释器是我从另一个文件导入的函数,具有'from rasa_nlu.model import Metadata,Interpreter' – hackerman
您可以仔细检查输出吗?你的例子在Python和JSON中都是非法的。 – DyZ