【发布时间】:2018-08-31 06:48:45
【问题描述】:
问题有所不同,在于预期输出如何处理 json。很抱歉浪费了您的时间。
我有一个 python 字典对象,我试图以字符串格式返回它,以便另一个函数进行字符串比较。我无法控制其他功能,因此我有责任以请求的格式返回。
现在我有这个 myfunction(params) 返回 (json.dump(dictionary object))
'{"Engineering": {"employees": 3, "employees_with_outside_friends": 2}, "HR": {"employees": 1, "employees_with_outside_friends": 1}, "Business": {"employees": 1, "employees_with_outside_friends": 1}, "Directors": {"employees": 1, "employees_with_outside_friends": 0}}'
但我希望返回看起来像我运行 print(dict) 时打印的常规字符串
{"Engineering": {"employees": 3, "employees_with_outside_friends": 2}, "HR": {"employees": 1, "employees_with_outside_friends": 1}, "Business": {"employees": 1, "employees_with_outside_friends": 1}, "Directors": {"employees": 1, "employees_with_outside_friends": 0}}
示例代码:
def get_actual_output():
dict_ = dict({"Engineering": {"employees": 3, "employees_with_outside_friends": 2},"HR": {"employees": 1, "employees_with_outside_friends": 1},"Business": {"employees": 1, "employees_with_outside_friends": 1},"Directors": {"employees": 1, "employees_with_outside_friends": 0}})
return(json.dumps(dict_))
expected_output = '{"Engineering": {"employees": 3, "employees_with_outside_friends": 2},"HR": {"employees": 1, "employees_with_outside_friends": 1},"Business": {"employees": 1, "employees_with_outside_friends": 1},"Directors": {"employees": 1, "employees_with_outside_friends": 0}}'
get_actual_output() == expected_output returns False
添加更多细节:
当我打印上述函数的返回值和预期值时,我得到的是:
>>> actual_output
'{"Business": {"employees": 1, "employees_with_outside_friends": 1}, "Dir
ectors": {"employees": 1, "employees_with_outside_friends": 0}, "Engineer
ing": {"employees": 3, "employees_with_outside_friends": 2}, "HR": {"empl
oyees": 1, "employees_with_outside_friends": 1}}'
>>> test['expected_output']
{'Business': {'employees': 1, 'employees_with_outside_friends': 1},
'Directors': {'employees': 1, 'employees_with_outside_friends': 0},
'Engineering': {'employees': 3, 'employees_with_outside_friends': 2},
'HR': {'employees': 1, 'employees_with_outside_friends': 1}}
【问题讨论】:
-
json.dumps已经返回,没有单引号。它使用双引号。下一个问题? -
json.dumps不返回包含单引号的字符串;单引号是字符串repr的一部分。 -
你只是打印错了。请出示minimal reproducible example的代码
-
字典中有布尔值吗?它们在 python 中看起来像
False,在 json 中看起来像false。 -
因此,在您添加的新细节中,
test['expected_output']根本不是字符串。这是一个字典。
标签: python json python-3.x