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

Learning
  • 65
  • 4

1 Answers1

0

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?

Danielle M.
  • 3,607
  • 1
  • 14
  • 31
  • Thank you for providing a solution. My string is good_test_string = '{"Nikhil":{"Akshat" : [{"a":2, "fs":1}]}}'. Want to convert it to dictonary format, so that I can extract the information. FYI: I exported data from MongoDB. – Learning Apr 12 '23 at 18:06
  • 2
    @Learning that string doesn't match what you posted in your original question, but it does work - I updated my answer. – Danielle M. Apr 12 '23 at 18:22