将列表表示为带双引号的字符串而不是JSON的单引号[重复]

时间:2022-09-15 13:02:54

This question already has an answer here:

这个问题在这里已有答案:

Input:

输入:

mylist = ["a", "b"]

I have to output:

我必须输出:

'["a", "b"]'

But using str(mylist) or '{}'.format(mylist) on the list gets me:

但是在列表中使用str(mylist)或'{}'.format(mylist)会让我:

"['a', 'b']"

This is for a JSON API, and JSON doesn't accept '.

这适用于JSON API,JSON不接受'。

Looking around, this is indeed stated that here it doesn't work with format for containers.

环顾四周,确实说明这里它不适用于容器的格式。

Is there still a solution? I'm now using .replace("'", '"') but that really seems silly.

还有解决方案吗?我现在正在使用.replace(“'”,“”),但这看起来真的很傻。

1 个解决方案

#1


7  

Are you trying to output JSON? In that case you should use json.dumps:

你想输出JSON吗?在这种情况下,你应该使用json.dumps:

import json
json.dumps(mylist)

This outputs: '["a", "b"]'.

输出:'[“a”,“b”]'。

#1


7  

Are you trying to output JSON? In that case you should use json.dumps:

你想输出JSON吗?在这种情况下,你应该使用json.dumps:

import json
json.dumps(mylist)

This outputs: '["a", "b"]'.

输出:'[“a”,“b”]'。