converting str to dict python

Learning
test_string = '{"Nikhil":{"Akshat" : ["a":2, "fs":1]}}'

Want to convert to dict = {"Nikhil":{"Akshat" : ["a":2, "fs":1]}}

Found this post: Convert a String representation of a Dictionary to a dictionary

But won't work using ast or json.loads(test_string). It seems that it's the list ["a":2, "fs":1] cause problems. Could someone please provide suggestions on it?

Thank you.

corrected, should be this test_string = '{"Nikhil":{"Akshat" : [{"a":2, "fs":1}]}}'

Danielle M.

Your input string isn't valid json, so can't be parsed as json. If you fix the string, it should work:

import json

good_test_string = '{"Nikhil":{"Akshat" : {"a":2, "fs":1}}}'

output_dict = json.loads(good_test_string)
print(json.dumps(output_dict, indent=2))

{
  "Nikhil": {
    "Akshat": {
      "a": 2,
      "fs": 1
    }
  }
}

Update for new good_test_string from comment:

import json

good_test_string = '{"Nikhil":{"Akshat" : [{"a":2, "fs":1}]}}'

your_dictionary = json.loads(good_test_string)

works for me. Do you get an error?

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related