[英]convert string representation of a dict inside json dict value to dict
Hello all and sorry if the title was worded poorly. 大家好,如果标题措辞不佳,则感到抱歉。 I'm having a bit of trouble wrapping my head around how to solve this issue I have encountered.
我在解决如何解决遇到的这个问题时遇到了麻烦。 I would have liked to simply pass a dict as the value for this key in my json obj but sadly I have to pass it as a string.
我本来希望只将dict作为此键的值传递给json obj,但可悲的是,我必须将其作为字符串传递。 So, I have a json dict object that looks like this
所以,我有一个看起来像这样的json dict对象
data = {"test": "Fuzz", "options": "'{'size':'Regular','connection':'unconnected'}'"}
. data = {"test": "Fuzz", "options": "'{'size':'Regular','connection':'unconnected'}'"}
。 Obviously, I would prefer that the second dict value weren't a string representation of a dictionary but rather a dictionary. 显然,我希望第二个dict值不是字典的字符串表示形式,而是字典。 Is the best route here to just strip the second and second to last single quotes for the data[options] or is there a better alternative?
是在这里只删除data [options]的倒数第二个和倒数第二个单引号的最佳方法,还是有更好的选择?
Sorry for any confusion. 抱歉给您带来任何混乱。 This is how the json object looks after I perform
这是我执行后json对象的外观
json.dump(data, <filename>)
The value for options can be thought of as another variable say x and it's equivalent to '{'size':'Regular','connection':'unconnected'}'
选项的值可以视为另一个变量x,它等效于
'{'size':'Regular','connection':'unconnected'}'
I could do x[1:-1] but I'm not sure if that is the most pythonic way to do things here. 我可以做x [1:-1],但是我不确定这是否是最pythonic的做事方式。
import ast
bad_string_dict = "'{'size':'Regular','connection':'unconnected'}'"
good_string_dict = bad_string_dict.strip("'")
good_dict = ast.literal_eval(good_string_dict)
print(good_dict)
You will have to strip quotation mark, no other way around 您将不得不删除引号,而没有其他方法
Given OP's comments I suggest the following: 鉴于OP的评论,我建议以下几点:
json
module (or the format you've chosen) to load the data json
模块(或您选择的格式)加载数据 The data should look like this: 数据应如下所示:
raw_data = {"test": "Fuzz", "options": "{\"size\": \"Regular\", \"connection\": \"unconnected\"}"}
And the code should look like this: 并且代码应如下所示:
raw_options = raw_data['options']
options = json.loads(raw_options)
data = {**raw_data, 'options': options}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.