简体   繁体   中英

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. So, I have a json dict object that looks like this

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. 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?

Sorry for any confusion. This is how the json object looks after I perform

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'}'

I could do x[1:-1] but I'm not sure if that is the most pythonic way to do things here.

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:

  1. Set the environment variable to a known data format (example: json/yaml/...), not a specific language (python)
  2. Use the json module (or the format you've chosen) to load the data

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM