python json转储

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15272421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:39:55  来源:igfitidea点击:

python json dumps

python

提问by Delremm

i have the following string, need to turn it into a list without u'':

我有以下字符串,需要将其转换为没有 u'' 的列表:

my_str = "[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]"

i can get rid of " by using

我可以摆脱“通过使用

import ast
str_w_quotes = ast.literal_eval(my_str)

then i do:

然后我做:

import json
json.dumps(str_w_quotes)

and get

并得到

[{\"id\": 2, \"name\": \"squats\", \"wrs\": [[\"55\", 9]]}]

Is there a way to get rid of backslashes? the goal is:

有没有办法摆脱反斜杠?目标是:

[{"id": 2, "name": "squats", "wrs": [["55", 9]]}]

采纳答案by vikki

>>> "[{\"id\": 2, \"name\": \"squats\", \"wrs\": [[\"55\", 9]]}]".replace('\"',"\"")
'[{"id": 2, "name": "squats", "wrs": [["55", 9]]}]'

note that you could just do this on the original string

请注意,您可以在原始字符串上执行此操作

>>> "[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]".replace("u\'","\'")
"[{'name': 'squats', 'wrs': [['99', 8]], 'id': 2}]"

回答by Alex Spencer

json.dumps thinks that the "is part of a the string, not part of the json formatting.

json.dumps 认为"是字符串的一部分,而不是 json 格式的一部分。

import json
json.dumps(json.load(str_w_quotes))

should give you:

应该给你:

 [{"id": 2, "name": "squats", "wrs": [["55", 9]]}]

回答by slohr

This works but doesn't seem too elegant

这有效,但似乎不太优雅

import json
json.dumps(json.JSONDecoder().decode(str_w_quotes))

回答by Shruti Kar

You don't dump your string as JSON, rather you load your string as JSON.

您不会将字符串转储为 JSON,而是将字符串加载为 JSON。

import json
json.loads(str_w_quotes)

Your string is already in JSON format. You do not want to dump it as JSON again.

您的字符串已经是 JSON 格式。您不想再次将其转储为 JSON。